Share this page with someone:

Information Technology

The official blog of Infotechnologist.biz.

JangoMail Setup

Alright, I just had a good bout with the Jangomail API. Seemed easy enough, but I wanted to share my results with everyone. I am going to share a simply command to send a basic transaction email, in HTML, with an
attachment.

First off, create yourself an account at Jangomail. Secondly, make note of your username/password that you use to login to your account. Once you have that all together, open up some FTP program, and
connect to the jangomail servers. The Host is going to be clients.jangomail.com and the username/password are, of course, your username password. Take the attachments that you want to include in your
mail outs and insert them into the attachments folder. Simple as that. Now it's time to write some code, that is going to send out one basic test Transaction email. The code is below.

<?php
$client = new SoapClient('https://api.jangomail.com/api.asmx?WSDL');
$parameters = array
    (
        'Username'          => (string) 'JangomailUsername', 
        'Password'          => (string) 'JangomailPassword', 
        'FromEmail'         => (string) 'noreply@yoursite.com',
        'FromName'          => (string) 'Your Website',
        'ToEmailAddress'    => (string) 'test@test.com', // Your email address 
        'Subject'           => (string) 'Test Email', 
        'MessagePlain'      => (string) 'This will show if they don\'t support HTML at their email service.', 
        'MessageHTML'       => (string) '
<html>
<body>
<h1>Test HTML Email</h1>
<p>Test HTML email text goes here.</p>
<img src="http://www.yoursite.com/images/img.jpg" /> <!-- How to insert an image if you wish -->
</body>
</html>
', 
        'Options'           => (string) 'OpenTrack=True,ClickTrack=True,Attachment1=fileattachment.pdf'
 
    );
 
try
{
    $response = $client->SendTransactionalEmail($parameters);
    echo "Message(s) sent!";
}
catch(SoapFault $e)
{
    echo $client->__getLastRequest();
}
?>

Just make sure your attachment is named the exact same as it was in the attachments folder.

Very simple. The hard part for me was the attachment. At first I was trying to figure out how to get it uploaded to the FTP that I was running the Jangomail system from...then finally realized it had to be
loaded into your Jangomail FTP system to work.

Good luck, and hope this helps. Also their support systems are very helpful. I had some issues with the attachment systems, and they helped me work it out pretty easily. They have great developer support.

C++ Case/Switch Statement Warning

If you are a programmer of any kind, you are most likely familiar with the Case/Switch statement. This is simply a way in programming for you to do different things depending on the value of a variable. For example..if your working with a variable named abc. You might want to do different things depending on what the value is. The long way would be to put down a long if/else statement to deal with each potential value type. The easy way is to use a simple switch/case statement. No matter what language you are using, this will come into play at some point.

If you are using PHP a switch/case statement might look like follows:

<?php
$variable = 'test';
switch($variable) {
  case 'test':
  // do something
  break;
case 'test2':
  // do something
  break;
case'test3';
  // do something
  break;
}
?>

That is very simple. It's quite similar to JavaScript, but with a little different syntax. Now here is the tricky part. I don't know every language out there. However, quite a few of them have the same type of structure of Switch/Case statements. Then suddenly C++ throws you a loophole. In working with C++ it's just about the same as PHP. Except for one strange thing. If you initialize a variable inside of a switch/case statement you have to use brackets around each interior case when you are initializing a variable. Just something tricky that I had to figure out with a lot of trial and error.

Google Reader - The Ultimate Tool For Developers

In my career I have used a lot of productivity tools. I have used time trackers, invoice systems, project management systems, time management systems, calendars, to-do lists, productivity systems, personal management systems, personal databases, personal time management systems, communication systems, and virtually every type of application that is out there. However, in my entire career, one of the most productive tools I have ever used (to help me learn more) was Google Reader.

Within Google Reader you are able to set almost any RSS feed to get loaded into Google Reader. It basically becomes a one stop source for all possible reading material. This helps me to keep track of many different updates to third party systems, and updates to API's, and a variety of other information as well. They give me access to almost all development, self-help, and productivity blogs out there. It allows me to review them all in one place without having to go all over the internet. I highly recommend Google Reader to virtually anyway.

If you are a heavy reader, then you need Google Reader. If you have just one blog or reading source that you visit, then Google Reader won't really help you. If you have at least 2, then you will save time in your day by hooking them into Google Reader. This saves you a lot of time, because they are all in one place. Not to mention you get an advantage over reviewing traditional blogs. First off, Google Reader allows you to star/save them. It also allows you to tag them. You can do all of this inside Google Reader, when you can't normally do it inside the standard blogging systems. Which allows you to save information for later, and a variety of other things. I use Google Reader to review self help material, hobby material (video games, comics, and other hobbies), as well as development material. It's a great source of information. Not to mention it's built in subscription finder allows you to hunt down material online that you are interested in, and just throw it directly into that format. It's a great utility, and I recommend it to anyone.

Facebook Login

Disclaimer: The code within the post is NOT ready for a production environment. I have halfway pulled it out of Codeigniter and half formatted as you would need. So this is not usable in a production environment. It is ONLY meant to serve as examples.

I had to write about this. This was probably one of the most annoying things I have had to work with in a long time. I have found a lot of people online who have had very similar problems with this. I want to try and hopefully save someone a lot of stress and heartache from having to try to figure out the Facebook registration and login by themselves. I have had about 2-3 days worth of very aggravating trial and error. I figured out a few key points and thoroughly understand how this works, inside and out.

Step One: Create App

Create a facebook account (unless you already have one). Once that is created, go into Facebook and login. At the very bottom of the page,
once you login, you will see a "Developers" link. You have to go to the very bottom of the page. Click that link. At the top right hand corner of the screen, click "My Apps". At the top right of this page click, "Set Up New App". Follow the instructions from there. It's pretty simple. Just put in all of your information, and setup the return URL as your website address. This is VERY important. So if your website is http://www.letseatcheese.com, then that is what goes in your domain and URL settings. This is a very important step. Make sure you follow the instructions on this part very carefully.

Also note..if you can't get to the create app screen, then it might be because your Facebook account isn't authorized. IF that is the case, Facebook would return an error about having to register your account (either using your mobile number, or your credit card). Perform whatever steps are needed to verify that. Once you have all of that ready, your ready to go.

That's it. You have created the app. Inside the app settings please note your app information. You will need the APP Id, Secret Key, and API Key. You will need to make note of all of these. They are very important, as is the site url and site domain. 90% of the time you have issues setting this up, it's going to come down to some of that basic information being wrong.

Step Two: Registration

The first thing you have to do is setup a way for users to assign their user account (on your site) with a facebook system. This is what allows the automatic login to occur from Facebook. There has to be some type of communication initially between Facebook and your system in order to record the Facebook User ID. This is what allows your system to match up user accounts during the login process. To be honest with you, the entire registration process is very easy.

There are a variety of ways to set this up. However, I did not want to have to fight with some of the methods they present, so I used the more straight forward Iframe. It worked for me very well. You would simply add the following code to your registration form. So you have your standard registration form (where they can register) and then you have your facebook Connect code. This code allows for standard registration, along with setting up Facebook integration (so they can do facebook login).

<iframe src="http://www.facebook.com/plugins/registration.php?
             client_id=APP_ID&
             redirect_uri=REDIRECT_URL&
             fields=name,email"
        scrolling="auto"
        frameborder="no"
        style="border:none"
        allowTransparency="true"
        width="100%"
        height="330">
</iframe>

This simple block of code handles the ENTIRE UI interface. This creates the box, populates all the data, and handles the entire user interface. You replace APP_ID with the ID of your application (which I explained how to get earlier). Then you replace the REDIRECT_URL with the URL of the page you want the script to send the data to. This HAS to contain the same BASE URL that was configured when you created the app (I explained this in very good detail earlier). Please make sure that URL is the same. So it would be whatever the URL you set in your Application Information, with whatever page you want. So if your website was http://www.whatever.com and the page which you were going to use the process the data was process_facebook.php then you would put the redirect URL as http://www.whatever.com/process_facebook.php. That is all that is involved in setting up the UI.

The next step, is processing the registration. This is the step that let's us match our registration system, with the facebook registration system. It's a very simple process. Let's assume the file is the same as I mentioned above..."process_facebook.php". You would have pretty much exactly what I have below in the process_facebook.php. If you were using the exact same setup as me, then this file
would be in your root folder.

define('FACEBOOK_APP_ID', 'APPID');
define('FACEBOOK_SECRET', 'SECRETKEY');
 
  if ($_REQUEST) {
     $response = parse_signed_request($_REQUEST['signed_request'], FACEBOOK_SECRET);
 
 
     $user_data = array();
     $user_data['facebook_userid'] = $response['user_id'];
     $user_data['facebook_connect'] = 1;
     $user_data['email'] = $response['registration']['email'];
     $name = explode(" ", $response['registration']['name']);
     $user_data['first_name'] = $name[0];
     $user_data['last_name']  = $name[count($name)-1];
     $sql = "INSERT INTO user_information (first_name, last_name, email, facebook_userid, facebook_connect) VALUES ('" . $user_data['first_name'] . "','" . $user_data['last_name'] . "','" . $user_data['email'] . "','" . $user_data['facebook_userid'] . "','" . $user_data['facebook_connect'] . "')";
     if (mysql_query($sql)) {
          // Setup success message and redirect
     }else {
          // Setup failed message and redirect
     }
  } else {
    // Setup error message that request was empty
  }
}
function parse_signed_request($signed_request, $secret) {
  list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
 
  // decode the data
  $sig = base64_url_decode($encoded_sig);
  $data = json_decode(base64_url_decode($payload), true);
 
  if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
	error_log('Unknown algorithm. Expected HMAC-SHA256');
	return null;
  }
 
  // check sig
  $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
  if ($sig !== $expected_sig) {
	error_log('Bad Signed JSON signature!');
	return null;
  }
 
  return $data;
}
 
function base64_url_decode($input) {
	return base64_decode(strtr($input, '-_', '+/'));
}

First replace APPID with the application ID, then replace SECRETKEY with the application secret key. Both of these can be found inside the Facebook settings which I have explained earlier. Those two functions were ones that I have taken from Facebook examples. These handle what is needed to decode the operation, and beats having to right it all from scratch.

Step Three: Login

The next and final step to this entire process is the Login script. This is what I ended up having to fight with for so long. There are a total of 2-3 steps in this process. So it is more convoluted than it originally seems. The first step is to deal with the user having to login/register or whatever else is needed. During the first step here a variety of things happen. If the User is not logged into facebook then they are prompted to login to it. If they are then it bypasses this step. Secondly, it checks if they have authorized this application to get access to their information. If they have then it skips this step, if they haven't then it prompts them to do so. So the front end flow is described below:

  • User clicks link.
  • If logged in then great. If not, then prompt for facebook login.
  • If authorized for this app then great, if not them prompt for authorization from user
  • If they decline auth, then it redirects them to fail page. If they approve or have already approved it handles Login automatically
    behind the scenes

That is the general flow of this entire situation. Now let's see how all of this runs on the backend.

The first thing we need is to verify whether or not the user is currently logged into facebook, if not we need to require them to login via facebook. Facebook actually handles all of this for us. We just need to automatically point the users in the right direction. This is where we actually create our facebook link that says "Login Via Facebook" or "Connect Via Facebook" or whatever you want. The code is below:

<a href="https://graph.facebook.com/oauth/authorize?client_id=APPID&redirect_uri=REDIRECTURL">Facebook Connect</a></p>

This is where the important step comes in. The easy part is your app id. Just replace that with your app id. Now for the redirect URL. You need to put in the URL to the file that is going to process all of this. The thing is, this has to be a filename that you remember. Since we have to use this a few times...
Once they do this, it will handle their login, and authorization and everything else.

The next step is to deal with the processing using the following code (all found on facebook_connect.php in my script). So if your
redirect url is http://www.website.com/facebook_connect.php then that is where all of this code is going to go. In facebook_connect.php in your root folder on your web server.

<?php
$code = $_REQUEST['code'];
 
$url = 'https://graph.facebook.com/oauth/access_token?client_id=APPID&redirect_uri=REDIRECTURL&scope=offline_access&client_secret=APPSECRETKEY&code=' . $code;
$access_code = file_get_contents($url);
 
$url = 'https://graph.facebook.com/me?' . $access_code;
$data = json_decode(file_get_contents($url));
 
$sql = "SELECT * FROM user_information WHERE facebook_userid = '" . mysql_real_escape_string($data->id) . "'";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
	$user_id = $row['user_id'];
}
header('Location: <a href="http://www.cheetahseat.com/index.php/fblogin/autologin/'" title="http://www.cheetahseat.com/index.php/fblogin/autologin/'">http://www.cheetahseat.com/index.php/fblogin/autologin/'</a> . $user_id);
?>

That's all there is too it. Replace the app id, and secret key with your unique information from the facebook app you created. Now here is the catch...the return url here, HAS to be the exact same as it was on the previous link. In short, EVERYTHING has to happen on this one page. If you try to do ONE step of the process with a different return URL it will not work. Make sure the return URL on this page is the
EXACT same as the one you provided in the original anchor link. Or it will not work. It'll return a strange error like cannot verify URL or something. That is pretty much everything.

Codeigniter Integration

Setting this up with Codeigniter requires an additional layer of work. Trying to perform OAuth work through CI can be a pain. I ended up working around this, in a pretty secure manner. However, you might want to clean up and tighten up the security a little bit on the login process (perhaps secondary sessions or something just to make SURE that it's really secure). I did this code pretty quickly.

So I found a very easy way to do this. Basically you just create a facebook_connect.php in your root folder (outside of codeigniter). So you have your original anchor link in one of your codeigniter views. That links with a return url of www.website.com/facebook_connect.php. Then all of my code is in there. You can access Code Igniter's database information by putting the following code at the top of the page.

define('BASEPATH', '/system/');
require_once('system/application/config/database.php');
mysql_connect($db['default']['hostname'], $db['default']['username'], $db['default']['password']);
mysql_select_db($db['default']['database']);

This gives you full access to all Mysql functionality using standard mysql functions and stays connected to the Code Igniter database. Saves you a lot of time having to run all of this through a second database. Here is the trick though for Code Igniter. To make it secure
you need to take a few precautions. First of all redirect them to a strange URL so it can't be easily figured out. Pass the Facebook USER id. This is going to make sure that we are getting the right user from facebook. Then proceed to user that facebook user id to connect them to the database and match them with your User id. This adds a lot of extra security. User would HAVE to guess someones facebook ID in order to get access to the system. Then just do a standard login and redirect them back to your homepage (in logged in state.

Closing

There you go. I might enhance this later as I get more ideas. I tried to get all of my experiences out here as best I can. This was the first time I had setup facebook auth like this. It took me a total of 18 hours spread over 3-4 days to get this right. The main thing hanging me is I tried to use facebook_connect.php to handle one step, then facebook_connect2.php to handle the next step. Then I realized they had to be the exact same. That was something that I got hung up on the longest. Well good luck with your implementation, and I hoped that helped.

Xhtml to PDF - My Thoughts

I wanted to express my thoughts here about PDF generation in PHP. Doing this by default is pretty easy. You download FPDF (or the library of your choice), you install it, configure it, and set it up. Then generally you just build your PDF. I recently ran across a few different classes that have claimed to take an xhtml/css page, and convert it to a PDF. I wanted to test it out. So I downloaded a PHP conversion class, tried it out, and it works perfectly. This is a strange euphoria. Not to mention, it pretty much supported all CSS. So the next time your stuck fighting with a manual PDF build, especially on those troublesome reports...try a converter instead. Might be as simple as trapping your HTML into a variable, passing it into a function and your done. The one that I used works with any good formatted HTML and most CSS styling options (just not floats).

Just to save you some time, I have done a little research and gotten some of the best options together for XHTML to PDF generation in a variety of different programming languages.

These languages had easy to find ones. There were a few languages I had trouble finding one for (ASP, and a few other languages).
If I find any more good ones for any major language, I will come back and list it here later on.

My Favorite Webhost

My General Thoughts
So I wanted to share my thoughts pertaining to web hosting. They are kind of biased...but it is what it is. Throughout my entire web/application development career, I cannot describe how many hosts I have researched, intensely studied, or personally tried. I have personally tried a variety of them (tons of free ones, bluehost, 1and1, hostgator, godaddy, and many others). I have researched/reviewed more than i can name. The world of hosting changes every year. Every single year there are new things happening in the world of hosting. Companies shut down, companies down size, other companies get bigger, some get worse, some get better. It is always changing.

Let me start off by giving you some examples. These are all my personal opinions. If you do not agree, that is OK. These are not set in stone, they are just my thoughts. So let's start off simply. I always refer all of my clients to the host I am currently at. I always make sure I am at the best host I can find, with the best services, most features, and best support. I always choose the best that I can find (I am a perfectionist). If a host does not stay the best, and I get a hint of a better host, I change. So does all of my clients generally. Since I refer every new client to the host I am currently using.

So let's start with Bluehost. When I first started my career...about 7 years ago, they were an awesome host. They did everything I needed. They were simply amazing. So, I used them a long time. However, after awhile they started going down hill. They had a lot of downtime around the time I stopped using them. They had a lot of complaints in the forum. I was just trying to start a business and my site was down all the time. This was happening due to growing pains. They were starting to grow faster than they could support. They lost my business permanently at that point. Not because I did not like them, but because I knew they were no longer the best (at the time). By the way, they have gotten a lot better since then. I have heard a lot of good ratings. But generally once I get that impression about someone, I stay away from them. On top of that, I never really did like the way they had their CPanel setup, I checked recently and it's almost the same.

From there I went to Godaddy. They are "OK". They are too big for their britches I think. They are too popular, and too big. So they are very restrictive of their resources. Their other features (domain registration) is also a pain to me. So I eventually left them. They are huge. Not to mention some of the third party systems that I like playing around with can't be installed easily in Godaddy. This is just another negative. Everytime I have had a client on Godaddy I have ran into one issue or another.

After that was over, I went to 1and1. I fell in love with this host. I had used them a VERY long time. I currently can say I have really no complaints. Over a period of time however, I got sick of the setup. There are a lot of things I find annoying about it. The interface in their panel is not user friendly, it's just not what I am looking for anymore. After a lot of debating, and thoughts, I finally decided it was to leave the dinosaur that is 1and1 and find something a little more suited to my current needs.

My Final Decision
With a ton of looking, I ran into Host Gator. This ended up being the beginning of a beautiful relationship. Host Gator ended up being my favorite host, that I have ever had the pleasure of hosting with. I have a great deal of things i have liked about them...and every time I start to think I have ran out of ideas to love them, I notice something else that I like even more about the whole experience. I have listed some of those experiences below. I have had a lot of experiences with a lot of hosts, but none of them were quite so...enjoyable. I actually enjoy going through my panel and doing stuff with my websites now, this has really engaged me to take on a lot more personal projects than I previously was.

Downtime
The hosting company is a growing company, but their down time is very good compared to other hosts. I have seen a few blog posts online that describe heavily about the downtime, on a grade chart they come somewhere around 99%. They have really good down time, and I have noticed no issues whatsoever since I started using them.

Speed
This host is the fastest that I had used. I do a lot o custom development, sometimes I use Drupal, sometimes I use Wordpress, and sometimes I experiment with random third party systems. With 1and1 my own personal sites ran very slowly, because of their server.
When I moved everything over to Hostgator everything was almost instant. I noticed that all of my sites load almost lightning fast.
Makes it easier for me to get around, and perform development on new personal projects as well.

CPanel
The main thing I like about Hostgator is their supreme host gator setup. Their databases are all inline for one thing. SO you can
go into the system, setup a database/user and be done with it. It is very fast to set this up, and their CPanel runs so fast, that you
can add 5-6 databases within just a few minutes. Another great thing is their PHPMyadmin import is set at 50 gigs (more than most of the
hosts I have seen). So most of the time, I can upload whatever sized SQL files I need, saving me a lot of time having to bring out
Putty and doing it the manual way. Another thing, is their open database. Once you click "PHPMyadmin" it does checks to make sure your in the Cpanel. Then it brings up a directory of ALL the databases on your account. You can go through them all and review stuff, change stuff, and just work on them all in one interface. Since your logged into the master account, you are logged into all databases. It also doesn't disconnect you every few minutes of inactivity, so you can do something and come back to the database as you need. It does disconnect you
after a few minutes, but the time on it is a lot more...reasonable than 1and1.

That's not all. The way you setup domains and structures on the site is pretty good. Their is one issue (having to re-add add-on domains just to be able to reset the default directory), but that is an issue with Cpanel, not with Host Gator. I am just waiting on the developers of Cpanel to do something about that.

Language Support
I am a programmer also, so that means I like working with a variety of languages. The Host Gator standard server (I have business hostings) allows me access to a bunch of primary languages (PHP, Perl, Python, Ruby) and a few others. This is a great experience when I want to play around with a few other languages, or if I decide I want to build a few sites in some of those other languages. This is also great for experimenting, learning new skills, or practicing my usage of various languages. This is a major thing for me. Very few hosts offer a variety of languages..this increases the capacity for development by a great deal, even allows a programmer to perform experiments between a variety of languages. TO me, the more languages you have available, the better.

Domain Handling
Right now the way that Host Gator handles domains is very annoying. I am actually registering and managing my domains through 1and1, then sending the DNS servers to Host Gator. However, Host Gator even has a solution to this issue. During the month of February, they are going to release their own Domain Management Utility. This is going to solve all of my issues pertaining to the domain registration handling. Not to mention they are becoming their own Registrar. Right now, they go through ENom, and their prices are VERY expensive. To transfer a domain, your looking at 20 bucks. The register a domain, they are around 10-15. Almost triple the price of 1and1. The good thing, is once they setup themselves as their own registrar, they are going to be getting a great deal of discounts for their users. That means the prices might potentially get cut in half. This is something to look forward to, and it's happening this month (so less than a 30 day wait). This is going to address the only negative thing I had to say about Host Gator (meaning they would be even better then, than they are right now.

Support
I can't even describe the support. They have 24/7 phone and chat support. Every issue I have had so far (NO MATTER WHAT IT WAS) I opened a technical support ticket, ask my questions, and log off chat. They are always very nice, very knowledgable, and answer my questions the best they can. I have had no complaints with support whatsoever. They even discussed with me the ins and outs of the hosting panel as I had various questions about the way their CPanel was configured.

Overview
Overall...host gator is my favorite host. If something else gets better than them, I would consider changing...but I expect Host Gator to be on top throughout at least all of 2011, 2012, and most of 2013. By that point it just remains to be seen if they end up growing too big to support hosting in the majestic way they do now.

Closing
If you are interested in what I had to say about Host Gator, and want to try them yourself, then please either use the banner link on the right hand side of the page, or use the code "ninjakreborn" when signing up. This will get me credit for your signing up, as well as give you a 9.00+ discount on whatever your first package payment is. This is also a good way to support the time I put into this site, if you find any use out of it.

Dealing with Sessions and Cookies in PHP

PHP has powerful Session and Cookie handling features built in. You can have full use of sessions and cookies with built in core PHP functions, without a great deal of work. Sessions are generally used for short term state saving, while cookies are meant to store long term data in a users browser.

PHP Sessions

PHP session handling is very simple. There are 4 primary things you need to know. The first thing is the PHP start() and destroy()
functions. The second thing is how to set sessions. The third thing you should know, is how to access the session variables after
you have stored them.

Session Start and Session Destroy

The first and most important rule in dealing with PHP Sessions is "Sessions have to be started, unless the server is configured to auto-
start them". Most of the the time the server PHP Settings are not setup like this, unless a developer has changed them. This is
generally not recommended. This adds extra overhead and processing, and is not generally recommended. So the standard way to run
sessions is using session_start() function. It's a very basic function call, which doesn't require any parameters. This just tells
PHP to start the session handling system. It can be used at the top of every page that your wanting sessions to run in. It can
also be entered into a require/include file at the top of all of the pages, and then it's activated globally.

Below is a little example code:

<?php
session_start();
?>

You simply put that at the top of every page that you want to allow sessions. It's easier if you set this in a config file, or include file and just require that on every page of the site. This is assuming your doing a standard basic procedural site. If your using a framework of some kind, then generally this option is easily turned on within the framework of your choice as a configuration option.

The standard logout functionality is also very easy. You simply call the session_destroy() function.

<?php
session_start(); // Starts initial session handling
session_destroy(); // Destroys all currently saved sessions
header('Location: index.php'); // Redirects back to homepage, assuming index.php is the homepage.
?>

In this example, we are starting the session engine (so PHP has access to the destroy function) then we are destroying any Session
variables that have currently be set. Generally code like this is used on a logout page, which almost always redirects to some
location. So I have included a line of code to set a header in PHP to tell the browser to take them to index.php. That url can
be changed to whatever you want it to redirect them too.

That is all that is required to totally destroy a session and log someone out.

There is one more detail to keep in mind about session_start(). Make sure you always include it at the VERY top of your page.
It needs to be the very first line. If you even have 1 character of code before this, or one line of white space..then it is
going to register as headers already sent. In this case, it will not start the session, and generally will throw an error as well.

Saving Sessions

Saving a session variable is also very simple. It takes 1 line of programming to successfully save a session variable.

<?php
$_SESSION['variable'] = value;
?>

This simply sets a session named "variable" to a value of "variable". The name and value can be changed to whatever you want, even
another variable. These variables can be set to strings, numbers, or arrays. Pretty much any standard variable can be placed within a
session.

Below is a basic example of how you would go about setting up session information when someone logs in. This code is not
optimize or geared for a production environment. It was also not tested.

<?php
session_start();
$sql = "SELECT * FROM user_information WHERE username = '" . $username . "' AND password = '" . $password . "'";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['first_name'] = $row['first_name'];
$_SESSION['last_name'] = $row['last_name'];
}
?>

That would simply check to see if the person is logged in (assuming username/password were from a from, have been validated, and
were sanitized). From this point you could access the same sessions you have just saved. Let's assume you want to print their
first name and last name on a welcome page. You could do something like the example below:

<?php
echo 'Welcome: ' . $_SESSION['first_name'] . ' ' . $_SESSION['last_name'];
?>

That would print out their first and last name. This assumes you have set session_start() somewhere in your script.

Using Cookies for extended State Saving

So let's assume you don't want the sessions to get destroyed every single time someone closes their browser. Well that is what happens.
When they close their browser the server destroys the sessions and forget they even exist. Using a variety of session options people can
avoid this..but it takes additional resources that aren't needed. Or you could simple save the sessions into a database (Which I don't do very
often, but may blog about some time in the future). So what do you do? You use a cookie to allow the sessions to be re-set every time they come to the site.

So the general idea is simple. When you create the session you save a cookie of just the user id.

<?php
session_start();
$sql = "SELECT * FROM user_information WHERE username = '" . $username . "' AND password = '" . $password . "'";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['first_name'] = $row['first_name'];
$_SESSION['last_name'] = $row['last_name'];
setcookie('user_id', $row['user_id']); // Set a cookie for the user id.
}
?>

That is all you need to do to set a cookie. One extra line of code. Now in the situation where they return to the site it's time to retrieve it.
In general you would need a lot more. Like you would want to check if they are authorized to view certain pages or whatever else, but that is outside
the scope of this post. So let's assume you just want to check something when they come to the site. IF they have a session already, then great. We need
to do nothing. IF they don't then we can see if they have a cookie and do something with it. So here is what you could do:

<?php
session_start();
// If there is no session then let's see if we can get one from a cookie.
if ($_SESSION['user_id'] == '') {
// See if the cookie is set
if ($_COOKIE['user_id'] != '') {
$sql = "SELECT * FROM user_information WHERE user_id = '" . mysql_real_escape_string($_COOKIE['user_id']) . "'";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['first_name'] = $row['first_name'];
$_SESSION['last_name'] = $row['last_name'];
setcookie('user_id', $row['user_id']); // Reset the cookie just to be safe.
}
?>

That's it. It will check to see if they have a cookie, if they do it'll rebuild the session data (exactly as if they had logged in) and that's it.

Session ID

Just recently I ran across another nice PHP function that deals with obtaining the ID of the current session. This has a few good uses..for example, generally if your using a Shopping cart it's based on session.
You will generally use the session to store the cart, then retrieve the session when your done. I use to use extensive code to get the session ID, until I found this function. Below is a simple example:

<?php
session_start();
 
$session_id = session_id();
 
echo $session_id; // Outputs the session ID
?>

Disclaimer

Disclaimer: None of this code was tested thoroughly, and is not intended for a production environment. Use at your own risk, I take no liability from issues/problems that arise from using this same code.

Integrating CKFinder with the Codeignitor Framework (PHP)

I have become very familiar with Codeignitor, CKFinder, and CKEditor since I have been in business. Recently I have had the challenge of trying to integrate the CKEditor and CKFinder systems into the Codeignitor framework.

CKEditor is pretty easy to setup inside Codeignitor. All you have to do is just load all of the ckeditor files/folders into the root directory and then include the JS file and configure it like you would on any normal website. CKFinder is practically the same. All you really have to do is load the files to the server and specify were to find them when you create the instance, as well as do all of the configuration options and initial setup.

I have known how to do this for quite awhile. However recently I was approached with a challenge that I did not readily know how to accomplish. Basically I had multiple different user accounts, and each user account needed to have the ability to have their own folder to use with CKFinder. Normally CKFinder defaults to ckfinder/userfiles and it works all internally. I had a situation where I had to basically have a new folder (named the ID of the user) for each user. I went back and forth into the code trying to work this out, I dug through Google for hours, and I also spent a great deal of time in forums trying to get the answer.

Finally I ran across a stray post in the Codeignitor forums that did exactly what I needed. It was pretty easy to setup, and since I got it initially configured it worked great. Here are the steps I followed to get this implementation up and running with the least amount of stress. It was very affective and it has worked fine ever since it was setup, and it's been in a production environment for awhile.

1) Setup a new folder in the main directory (the same directory that contains your Codeignitor index file). I named my folder "ckfinder_userfiles". Once you setup the new folder, load it up to the server.

2) Now open the CKFinder config file. If you loaded your CKFinder folder into the server in the main directory then you can find the config file at the following location: /ckfinder/config.php

3) Once you have the file open we are going to assume that you have a session saved using codeignitor that is called "user_id" for example. It can really be anything but it will serve our purposes for this example. By default you need to look at line 61 but it could change if you have a custom setup for your config file. Your looking for the area where the base_url is setup. Just replace the base url parameter with the following code:

<?php
$session = unserialize($_COOKIE['ci_session']);
 
$user_id = $session['user_id'];
$baseUrl = '/ckfinder_userfiles/' . $user_id . '/';
?>

That is it. It will take the internal Codeignitor session and dig out the user_id and use that to build the base url. Now anytime that user is logged in (assuming the user_id is set as a session to their user id, then it will automatically default internally to the folder ckfinder_userfiles/theirid. It also handles all of this automatically so you don't have to worry about doing anything to the folder or creating it. CKFinder will create it automatically. The good part is this restricts user across the board to only entering their one folder. So this prevents people from getting into other people's folder (Which can be a problem if you are needing to restrict users to only their specific folders.

There are probably other solutions to this problem. I found this specific solution to be very effective, and seemingly very secure. I would be interested to hear about other people's thoughts regarding this procedure, or maybe things they have tried in their own implementations. Feel free to comment.