Secure PHP Site using Sessions

Discussion in 'PHP' started by SiteBuyerUK, Mar 26, 2007.

  1. #1
    Hey,

    I am creating a secure php site using sessions, so with my site i have the following sessions check which is ran on every page:

    <?php
    
    session_start();
    
    if(isset($_SESSION['user'])) {
    
    	
    	if($_SESSION['useragent'] != md5($_SERVER['HTTP_USER_AGENT'])) {
    	
    		session_unset();
    		session_destroy();
    		session_start();
                    session_regenerate_id();
    
    	} else {
    
    		session_regenerate_id();
    
    	}
    
    }
    
    ?>
    PHP:
    The user and useragent values are created when a user successfully logs in using the login form on the site, on each page they visit the session is regenerated.

    My questions are:

    1. Can i improve the security of this somehow?

    2. Should i regenerate the session id on every page if the session is successful, i mean is there any need (i could just regenerate on login), will it slow the page times down if the server is recieving high amount of visitors?

    Thanks!
     
    SiteBuyerUK, Mar 26, 2007 IP
  2. Robert Plank

    Robert Plank Peon

    Messages:
    55
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    By "secure" you literally mean HTTPS (SSL) or just regular password protected HTTP?

    What is the point of storing the browser name? Why not just base it on the username and password?
     
    Robert Plank, Mar 26, 2007 IP
  3. SiteBuyerUK

    SiteBuyerUK Peon

    Messages:
    253
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    0
    #3
    HTTP

    The useragent is an extra layer of protection, it means a hacker trying to access the site with a users session id, wouldnt be able to if they had a different browser.

    This is based on the username and password, a hacker cant edit the session data, and the username is only written to the session id on a successful login using the username and password.
     
    SiteBuyerUK, Mar 26, 2007 IP
  4. Robert Plank

    Robert Plank Peon

    Messages:
    55
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Oh ok... that's actually a cool way to prevent session hijacking. But you don't have to calculate the md5 hash of the user agent string... since it's stored on the server and not as a cookied value.

    Better do a session_regenerate_id(TRUE) instead though... so that it destroys the old session.
     
    Robert Plank, Mar 26, 2007 IP
  5. SiteBuyerUK

    SiteBuyerUK Peon

    Messages:
    253
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thanks for that little tip Robert i didnt know about session_regenerate_id(TRUE) :D
     
    SiteBuyerUK, Mar 26, 2007 IP