Thursday, October 11, 2007

Using Sessions in PHP

Introduction Building web applications with membership management is one of the most frequent tasks that every programmer does. Managing membership data, such as username, password and the member's profile with sessions in PHP is the easiest and simplest solution, although it is not the only one. Preparation With this tutorial, I assume you are using PHP 4.1.0 or the later. The first thing that we should know to use sessions is that you have to initialize the session. session_start(); Any script which has that line would make the script available to register a new session or read an existing session which weÂ’ve defined on another page. Enough of the blah blah stuff, shall we now go to the example stuff?

Basic Sessions Go to this page"; ?> The above example shows you that I create a session variable named "real_name" storing my name as the value. Then on the second page, I print out the session variable and my name will show up. LetÂ’s do another example: When you first access that page, it will display 1. Try to refresh the page and the number will grow. To destroy or delete an existing session variable, you can use the unset command. unset($_SESSION["session_name"]); Or if you want to delete all session variables (and the session itself), you can do it by using the destroy command. session_destroy(); The destroy command is usually used to log-off a user from the membership area. LetÂ’s make a membership area for our example.

Running Membership with Sessions In the first page, I stated that sessions are usually used to create a membership management. Now, I want to show you a little snippet to create a login system, which you have to complete to create your own membership management. Your username is empty."; if (trim($password) == "") $error .= "
  • Your password is empty.
  • "; /* from here, do your sql query to query the database to search for existing record with correct username and password */ if (trim($error)!="") return $error; } function login ($forms) { $username = $forms["username"]; $password = $forms["password"]; /* do your sql query again, but now returning the id of member */ return $member_id; } ?>
    Username :
    Password :
    In the above example, we have built three pages. The first page is functions.php. In this page we build all the functions to do login checking, the login and the login detector. The second page is login.php. We will show the login form to our user and do some processes to register sessions when they have passed the login check. Third and the last page is the sample of how to use the system. This page is only available when user has logged in or has the session variable "member_id" with some value, not null.

    Another Example Still don’t understand how to use sessions? Here is another example for you. Let’s make an online user counter using sessions. Step 1: Make a database table with 2 fields: NAME TYPE onlineuser_session varchar(100) onlineuser_time varchar(30) Step 2: Download the dbal from my site: here. Step 3: Make these files db = $db; $this->table = $tblcounter; $this->sid = session_id(); $this->do_count(); } function do_count () { if ($this->is_logged()) $this->update_log(); else $this->new_log(); $sql = "SELECT COUNT(onlineuser_session) as total " . "FROM {$this->table} " . "WHERE onlineuser_time=’".(time()-60)."’"; $this->db->Query ($sql); $RS = $this->db->FirstRow(); $this->online = $RS["total"]; } function new_log () { $sql = "INSERT INTO {$this->table} " . "(onlineuser_session, onlineuser_time) " . "VALUES (‘{$this->sid}’,’".time()."’)"; $this->db->Query ($sql); } function update_log () { $sql = "UPDATE {$this->table} " . "SET onlineuser_time=’".time()."’ " . "WHERE onlineuser_session=’{$this->sid}’"; $this->db->Query ($sql); } function is_logged () { $sql = "SELECT * FROM {$this->table} " . "WHERE onlineuser_session=’{$this->sid}’"; $this->db->Query ($sql); if ($this->db->RowCount>0) return true; else return false; } }; ?> online; ?>

    Writing a Basic Authentication System in PHP

    Storing Passwords Before we can begin coding with PHP, we need to first take a brief look at passwords. There are many different ways to manage and store a user's login ID and passwords, but one common method is to store them in a database. For security purposes, the passwords themselves should not be stored in the database in a plain text manner. Instead, the password can be processed by a one-way, irreversible encryption or hashing function and then the jumbled result is what is actually stored. That means the password supplied later will need to be encrypted/hashed before we compare it with the stored value. If they both match then we know the password is good. PHP's sha1 function should suffice for our purposes. It accepts a string and returns a 40 character hexadecimal hash representation. This hash cannot be converted back to the original string. The following is an example of sha1 in action: We'll assume for this tutorial that a database table named Users exists which stores the username and passwords hashed with the sha1 function. It's common mistake to not make the password column large enough to store the entire hash. Using sha1, the column should be 40 characters.

    Getting the User Login An HTML form is used to obtain the user's login credentials. The form displays 2 input fields--one to obtain the login ID and another to obtain the password.


    The userid input field accepts the user's login id while the password field will accept the user's password. The password field might show asterisks or dots as the value is entered, but remember that the form will send it's data in clear text. A secure connection should be made using HTTPS. For more information on that subject see my tutorial Generating Your Own Security Certificates For Use With Apache/HTTPS. The form here submits its information to a script named validate.php as specified by the form's action attribute. It's that script that will be responsible for checking the user's login ID and password in the database and allowing the user to continue.

    Processing the Login The actual authentication can take place once we have the user's login ID and password. We need to encrypt or hash the password the same way it was initially done. $user = $_POST["userid"]; $pass = sha1($_POST["password"]); With the ID and password value, we can query the database for any matching records. The following SQL statement is designed to return records where the login ID and password hash match. SELECT * FROM Users WHERE User = '$user' AND Password = '$pass' If the query returns a record set then the login credentials are valid and the user may have access to the protected information. If the query fails to return a record then the credentials are invalid and access is denied. The validate.php script that would accomplish all of that might resemble the following: Instead of simply echoing "Access Granted" or "Access Denied" as shown here, your script can set cookies or start sessions, redirect the user to the login form or perform whatever else is needed.

    Alternating row colors with PHP and mySQL

    First Things First Why am I writing this? Well, frankly I am tired of answering the same question over and over and would like a place to just point people for an answer. Besides that, I am guessing that there are other people who can benefit from this that just aren't asking the question. The examples in this tutorial are using PHP and mySQL. But, the theory can easily be applied to any other programming language or database system. Just use your noodle (that's your brain) and I am sure you can figure it out. Ok, the first thing we are going to do is get our data from our database. I'm not going to go into alot of detail here. I will just show you the code. Next we will display the data. It's as simple as that. The whole key to displaying the data in the way we want is the modulus operator (%). What does the modulas operator do you ask? It simply gives us the remainder of a division. So, 3 % 2 returns 1, 3 % 3 returns 0. Easy huh? Ok, on with the code to do this.

    Let's Do It First off, let's get some data from our database. Let's assume we have a table called mytable with 3 fields: name, phonenumber, and age. Ok, we have our data from our database. Now we just need to open up our table and run a for loop for as many rows as we have and display the data. Then, we close the table. \n"; echo "NamePhoneAge\n"; for($i = 0; $i < $numofrows; $i++) { $row = mysql_fetch_array($result); //get a row from our result set if($i % 2) { //this means if there is a remainder echo "\n"; } else { //if there isn't a remainder we will do the else echo "\n"; } echo "".$row['name']."".$row['phonenumber']."".$row['age']."\n"; echo "\n"; } //now let's close the table and be done with it echo "\n"; ?> That's it. Really. That's all there is to it. It's so simple that it is amazing. Now, get out there and fancy your tables up!