MySQL
  Home arrow MySQL arrow Security and Sessions in PHP
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
MYSQL

Security and Sessions in PHP
By: Jason D. Agostoni
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 54
    2003-08-21

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Learn how to secure your PHP pages swiftly using a simple include file that should be included at the top of every page. Read more ...This article demonstrates an easy way to maintain sessions and security (or authorization) in PHP. It does NOT use the PHP built in session support.

    The following method will allow you to easily secure any PHP page by simply including a file at the top of every page. In this tutorial you will:

    a) Create your database structure
    b) Create a login page
    c) Create your security check include file
    d) Secure your site

    There are many different ways you can modify this technique to suit your own needs. Some of these ideas will be listed at the end of this article.

    Step 1: Store your data

    In order to authenticate your users, you must store their information somewhere. That location can be a flat text file or a database server. In this tutorial, we will use a MySql database. Given that you probably already have a database you wish to use, this article will focus just on one table: tblUsers.

    This table will store all of your user information but we will only focus on the fields necessary to this article. The following fields are required:

    iUser - This will be a unique ID used in the table.
    sEmail - We will use the email address as the login
    sPassword - We will need this to authenticate the user
    sGUID - This is the field to store the users current session ID
    sData - This is where you can store various session information about the user.

    To create this table in MySql, execute the following DDL:

    CREATE TABLE tblUsers (
    iUser int(10) unsigned NOT NULL auto_increment,
    sEmail varchar(255) NOT NULL,
    sPassword varchar(255) NOT NULL,
    sGUID varchar(32),
    sData text,
    PRIMARY KEY (iUser)
    ) TYPE=MyISAM;


    In the interest of space and time, this article will assume you can build your own "Add User" form and we will use the following DML to add a user for demonstration purposes:

    INSERT INTO tblUsers Values
    (
    Null,
    'test@user.com',
    password('testpass'),
    Null,
    Null
    )


    Note the use of MySql's Password() function. This is a one-way function so you will not be able to "retrieve" the user's password. There are other options you can use besides the Password() function such as a md5 hash or your own cipher. The Null value for the iUser field triggers the auto_number function and will generate a unique ID for us. The user we just created has an email/username of test@user.com and a password of testpass.

    Step 2: Create a login page

    You will need a way to authenticate your users as they enter the system. You will create a login page in such a manner that it can intercept a user going to any secured page in your system. Once the user has logged in they will be redirected back to the page they were attempting to access.

    First, we need a simple HTML form so save the following HTML as Login.php:

    <html>
    <head><title>Login</title></head>
    <body>
    <form action="LoginAction.php" method="Post">
    Email Address:<br />
    <input type="Text" name="psEmail" />
    <br />
    Password:<br />
    <input type="password" name="psPassword" />
    <br />
    <input type="submit" value="Login" />
    <input type="hidden" name="psRefer" value="<? echo($refer) ?>"
    </form>
    </body>
    </html>


    The obvious parts of this login page are the email and password. The hidden field psRefer will be a query string variable that is passed to this page, which represents from where the user entered the web site.

    Next, we need a page that will actually authenticate the user against the data in the database. If the user is successfully authenticated a GUID will be generated and they will be on their way. If they are NOT authenticated they will be sent back to the login page. The following code should be saved as LoginAction.php:

    <?php
    // Check if the information has been filled in
    if($psEmail == '' || $psPassword == '') {
    // No login information
    header('Location: Login.php?refer='.urlencode($psRefer));
    } else {
    // Authenticate user
    $hDB = mysql_connect('server', 'user', 'pass');
    mysql_select_db('database', $hDB);
    $sQuery = "
    Select iUser, MD5(UNIX_TIMESTAMP() + iUser + RAND(UNIX_TIMESTAMP())) sGUID
    From tblUsers
    Where sEmail = '$psEmail'
    And sPassword = password('$psPassword')";
    $hResult = mysql_query($sQuery, $hDB);
    if(mysql_affected_rows($hDB)) {
    $aResult = mysql_fetch_row($hResult);
    // Update the user record
    $sQuery = "
    Update tblUsers
    Set sGUID = '$aResult[1]'
    Where iUser = $aResult[0]";
    mysql_query($sQuery, $hDB);
    // Set the cookie and redirect
    setcookie("session_id", $aResult[1]);
    if(!$psRefer) $psRefer = 'index.php';
    header('Location: '.$psRefer);
    } else {
    // Not authenticated
    header('Location: Login.php?refer='.urlencode($psRefer));
    }
    }
    ?>


    The first objective of this code is to verify that a username and password were sent and otherwise return to the login page. This is just some rudimentary protection against some hacking. Next, the code connects to a database and tries to retrieve the user data matching the credentials sent from the Login.php page. If there is no match in the database the user is returned to the login page.

    If there is a match the user record is updated with a GUID and a cookie is set on the user's computer. You do not have to use cookies here but this prevents you from having to put the session id on the URL of every page. After the cookie is set, the user is either sent to the referring page or to a default page (in this example: index.php).

    To generate the GUID or session ID, you need to generate a unique number and hash it to protect would-be hackers from brute-forcing their way into your application. This article used MySql's built in MD5 function with a formula to help generate a random seed. You can use PHP's hashing functions or any other method of generating random hashes here.

    Step 3: Create an include file

    Now that you have a login mechanism, you need to create a page that will easily protect any page in your web site by simply including it. To make this "smart" page you just need to check the user's session ID that is stored in their cookie against the database. If there is a match then the user has logged in otherwise they should be redirected to the Login.php page. Here is the PHP code to perform that (call it incSession.php):

    <?php
    // Check for a cookie, if none got to login page
    if(!isset($HTTP_COOKIE_VARS['session_id'])) {
    header('Location: Login.php?refer='.urlencode($PHP_SELF.'?'.$HTTP_SERVER_VARS['QUERY_STRING']));
    }
    // Try to find a match in the database
    $sGUID = $HTTP_COOKIE_VARS['session_id'];
    $hDB = mysql_connect('server', 'username', 'password');
    mysql_select_db('database', $hDB);
    $sQuery = "
    Select iUser
    From tblUsers
    Where sGUID = '$sGUID'";
    $hResult = mysql_query($sQuery, $hDB);
    if(!mysql_affected_rows($hDB)) {
    // No match for guid
    header('Location: Login.php?refer='.urlencode($PHP_SELF.'?'.$HTTP_SERVER_VARS['QUERY_STRING']));
    }
    ?>


    The first part of the code checks to see if there is a cookie set with the session ID otherwise it will redirect the user to the Login.php page. If there is a valid session ID the script will try and match it against the database. If there is not a match the user is redirected to a Login.php page. Otherwise, the user is allowed to continue onto the page they were trying to access. To add this security to a page in your application, simply add the following code to the top of the page:

    <?PHP require('incSession.php'); ?>


    Now you have secured your application! Once you get over the initial creation of the Login and actions pages you only need to add the one line of code above to secure any page in your web. Here is a list of modifications you can make to the above implementation to make the script even better:

    Expiration - You can have the login expire by adding a logged-in date field to tblUsers. You would need to check that date against your "timeout" in incSession.php.

    Security Levels - You can add a field to tblUsers to specify the user's security clearence. Then you can compare that value against a variable that you have defined on each secured page. For example you could put the following at the top of your secured page:

    <?PHP
    $giSecurityLevel = 3;
    require('incSession.php');
    ?>


    After that, the script could return the user's security level in incSession.php and compare it against $giSecurityLevel. If the user's level is below the required level the script can redirect them to a "no access" page.

    Store/Retrieve Session Data - You can use the sData field to store the user's session information (like a shopping cart, for example) as a formatted string or even XML data. The choice is entirely yours since it is a large text field.

    Conclusion

    Using the script above will assure that you have a simple and foolproof method of securing your web site. There are many other methods available (PHP sessions, .htaccess, etc.) and each has their strengths and weaknesses. I believe this method to be one of the most portable and easily customized methods available.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More MySQL Articles
    More By Jason D. Agostoni

     

    IBM® developerWorks developerWorks - FREE Tools!


    Check out the new Jazz space on developerWorks

    <a href="http://zeus.developershed.com/shonuff.php?blackbird=3853&zoneid=442&source=&dest=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fspaces%2Fjazz%3FS_TACT%3D105AGY31%26S_CMP%3DDEVSHED&ismap="><img src="http://images.devshed.com/corp/img/news/jazz01.gif" alt="developerWorks Jazz space" align="left"></a>You've heard the buzz about Jazz... want to know more about it from a developer's perspective? Check out the Jazz space on developerWorks. This space is an up-to-date resource for developers, including technical information about Jazz and products built on Jazz, like Rational Team Concert Express. The Jazz space includes content from a wide variety of sources, including links, feeds, and comments from experts.
    FREE! Go There Now!


    IBM – Taking Web 2.0 to Work

    You'll get answers to many questions and more from David Barnes, Lead Evangelist for IBM Emerging Internet Technologies. David will discuss aspects of Web 2.0 that bring value to corporations, academia, and government. He'll also discuss IBM's vision around Web 2.0, including the importance of remixability and consumability. The discussion will culminate with examples of various IBM Software Group solutions you can use to get ahead of the Web 2.0 adoption curve.
    FREE! Go There Now!


    NEW! Application Development Tools for the Mainframe Developer

    You probably have thousands of lines of COBOL code loaded with business intelligence and being used to run your business, along with an army of developers maintaining these applications. Learn how to prepare your applications and developers so you can keep that competitive edge and move to a service-oriented architecture with the IBM Rational Enterprise Modernization solutions. Replay is available for 9 months.
    FREE! Go There Now!


    NEW! Innovate don't duplicate! Asset reuse strategies for success

    Asset Reuse is a key strategy for companies looking to create innovative solutions to solve complex software development problems. Searching for, identifying, updating, using and deploying software assets can be a difficult challenge. Listen to this webcast, to learn about strategies and tools that you can leverage for a successful project, including Rational Asset Manager, Rational Software Architect and WebSphere Service Registry and Repository.
    FREE! Go There Now!


    NEW! Project and Portfolio Management Executive Resource Kit

    Portfolio Management is about effectively managing portfolio value by aligning portfolio investments with business goals. This complimentary e-kit provides a collection of materials that can help you understand how IBM Rational enables and automates best practices for improved governance and clear visibility into portfolio and project performance across the entire IT project lifecycle.
    FREE! Go There Now!


    NEW! Successful Change and Release Management for .NET

    Join this webcast to discover the key requirements for successful change and release management. Learn how to extend your .NET environment to improve productivity and collaboration, and address core problems afflicting team development. In this webcast, we’ll review typical challenges faced by customers and how to resolve them with the IBM Rational Change and Release Management solution, including Rational ClearCase, Rational ClearQuest and Rational Build Forge. Replay is available for 9 months.
    FREE! Go There Now!


    NEW! Using IBM Rational Developer for System z and IBM Rational ClearCase together to manage application development

    Whether you are creating new applications or modifying existing ones, managing integration of new components with traditional z/OS elements is a critical part of building and deploying modern applications. Listen to this webcast to see how IBM can help you optimize your development process using an IDE like Rational Developer for System z that integrates with management tools, such as ClearCase to manage your application development on mainframes.
    FREE! Go There Now!


    NEW! Webcast: Eclipse: Empowering the universal platform

    The Eclipse community is constantly working to extend Eclipse's functionality. In this webcast, learn about some of the most important and feature-rich projects under development. From multi-language support to plug-in development, tune in to see what Eclipse is capable of now.
    FREE! Go There Now!


    NEW! Webcast: Introducing the new Information Server and Solutions community: LeverageInformation

    User communities play an important role in communication and collaboration around products, solutions and other areas of special interest to members. Successful communities are able to provide the right mix of content and services to deliver a value proposition that resonates with each audience. Join Tom Inman, VP of Marketing for Information and Platform Solutions as he introduces the new LeverageINFORMATION community. During this webcast, learn about the value provided by the community and how customers and partners derive value from the community in addressing their own technical and business challenges.
    FREE! Go There Now!


    Refresh! IBM Rational Systems Development Solution eKit

    With IBM Rational Systems Development Solution, you can deliver products faster with higher quality. Within this kit, Read the “Model Driven Systems Development” white paper to see how to improve product quality and communication. Then check out the rest of the e-Kit to learn more about important topics that can affect the success of any software project through customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems. From start to finish, at every stage in your projects, Rational Systems Development Solution can help your company reach its full potential.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    MYSQL ARTICLES

    - MySQL and BLOBs
    - Two Lessons in ASP and MySQL
    - Lord Of The Strings Part 2
    - Lord Of The Strings Part 1
    - Importing Data into MySQL with Navicat
    - Building a Sustainable Web Site
    - Creating An Online Photo Album with PHP and ...
    - Creating An Online Photo Album with PHP and ...
    - PhpED 3.2 – More Features Than You Can Poke ...
    - Creating An Online Photo Album with PHP and ...
    - Creating An Online Photo Album with PHP and ...
    - Security and Sessions in PHP
    - Setup Your Personal Reminder System Using PHP
    - Create a IP-Country Database Using PERL and ...
    - Developing a Dynamic Document Search in PHP ...







    © 2003-2010 by Developer Shed. All rights reserved. DS Cluster 12 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek