SitePoint Sponsor

User Tag List

Results 1 to 10 of 10
  1. #1
    SitePoint Enthusiast
    Join Date
    May 2009
    Posts
    47
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Authentication and Session Management?

    I want to clarify my understanding of how to implement authentication and (db based) session management in an environments that uses load-balancing/clustering of web server, db servers, etc..

    From what I understand, once the user submits the login form, those values are checked against the db and if matched a hashed cookie signifying authentication is created and the hash value is also stored in a session table. This cookie's existence is checked for each page that requires authentication.
    When values need to be saved to the session, those values are inserted as name-value-pairs into the row within the session table that has the matching hash value (to the cookie). Lastly, when the user logs out, the cookie and the row in the session table are deleted.

    If any part of the above is incorrect, please let me know. Additionally, if the above is correct, how does one handle the situation where the user doesn't log out? Sure, if the cookie is set to expire when the browser closes it will be deleted, but what about the values in the session table?

    Thanks.

  2. #2
    SitePoint Member
    Join Date
    Dec 2008
    Posts
    21
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    For pruning, you can set up a cronjob to cleanup old session records. Or (if your website is small and has no cron) you user random numbers function to create a fixed chance that the session prunning is run. You would have a function like maybe_prune_sessions() that is triggered upon every request. It would roll the dice, so to say, and once in a while the actual pruning would happen.
    Caffeine Web Framework - reinventing the wheel since 2004.
    MicroWSS - simple SOAP web services server in Java.

  3. #3
    SitePoint Enthusiast
    Join Date
    May 2009
    Posts
    47
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by dan06 View Post
    This cookie's existence is checked for each page that requires authentication.
    Is only the cookie's existence checked? Or is the value of the cookie checked?

    For example, lets say a user logs in and has two cookies set:
    1. user name 2. hashed session id

    Are both these values checked against a session table on each page view that requires authentication?

  4. #4
    SitePoint Enthusiast
    Join Date
    Jul 2005
    Location
    Norway
    Posts
    88
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi

    If you use the "session_set_save_handler" function to set a class to be your session-handler, then there's a gc (garbage collection) method you can implement which will be called every once in a while. Then you can just delete records that are older than a certain date.

    It's important to update each row's "lastSeen" whenever the session is loaded or changed. This way you will be able to know which sessions have been inactive for a long time.

    If you google for "session_set_save_handler" and "tutorial" you'll probably find info on how to implement it.

  5. #5
    SitePoint Member
    Join Date
    Feb 2007
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I agree, look into session_set_save_handler, don't go invent it all over again...

  6. #6
    SitePoint Guru
    Join Date
    Oct 2006
    Location
    Queensland, Australia
    Posts
    852
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sessions are usually not the only things needed to be cleaned up on a regular basis in a PHP application. Old shopping carts, logs and various other things also need to be cleaned up at some point, and I find cronjobs and the other aforementioned solutions to be unreliable or impractical, especially if you want to make your application portable.

    For that reason, I'd suggest you have a file or database table to store persistent maintenance information. The information stored would need include the last time that particular maintenance routine was carried out, and possibly also the interval for which it should be carried out, if you wish to set unique intervals for different maintenance tasks.

    Here's a working example class and file to represent what I'm talking about:

    PHP Code:
    <?php

    class ApplicationMaintenance
    {
        protected 
    $sxml;
        protected 
    $maintenanceFile;

        public function 
    __construct ($maintenanceFile)
        {
            
    $this->sxml simplexml_load_file($maintenanceFile);
            
    $this->maintenanceFile $maintenanceFile;

            
    // Loop through tasks.
            
    foreach($this->sxml as $task)
            {
                if( (
    time() - (int) $task->interval) > (int) $task->lastRun )
                {
                    
    $this->{'task'.str_replace('_'''$task['id'])}();
                    
    $task->lastRun time();
                    
    $taskRun true;
                }
            }

            if(
    $taskRun true)
            {
                
    $this->saveToConfig();
            }
        }


        protected function 
    saveToConfig ()
        {
            
    $file fopen($this->maintenanceFile'w');
            
    fwrite($file$this->sxml->asXML());
            
    fclose($file);
        }


        
    /***********************************************/
        /***            Maintenance Tasks            ***/
        /***********************************************/


        
    protected function taskCleanSessions ()
        {
            
    // Perform maintenance task.
        
    }


        protected function 
    taskCleanAccessLogs ()
        {
            
    // Perform maintenance task.
        
    }

    }
    Code XML:
    <?xml version="1.0"?>
    <tasks>
    	<task id="clean_sessions" desc="Cleans out old sessions.">
    		<interval>864000</interval> <!-- 10 days -->
    		<lastRun>1254774326</lastRun>
    	</task>
    	<task id="clean_access_logs" desc="Cleans out old access logs.">
    		<interval>2592000</interval> <!-- 30 days -->
    		<lastRun>1253672762</lastRun>
    	</task>
    </tasks>

    The only negative to this solution that I can think of, is that it adds a minuscule overhead to your application, but it's so tiny it's not worth worry about. A single SQL querying is probably more taxing.

  7. #7
    SitePoint Evangelist
    Join Date
    Mar 2005
    Posts
    423
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That's quite a nice example, but there's a wee bug in that code.

    Code:
    		
                    if($taskRun = true)
    		{
    			$this->saveToConfig();
    		}
    surely should be...
    Code:
                    if($taskRun === true)
    		{
    			$this->saveToConfig();
    		}
    ...and it might be better to initialise $taskRun = false before the foreach begins, so the variable is already in a determined state

  8. #8
    SitePoint Enthusiast
    Join Date
    Jul 2005
    Location
    Norway
    Posts
    88
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That's a pretty cool example of how to do cron jobs from php

    Some jobs might take a long time, so if you don't detach it from the current request, one of the site's users is going to have to wait for a long time for the cron to finish it's work, and he might cancel the request or it might time out.

    As a workaround one could call a php script with exec('php cron.php &'). This will (with the '&') make the process a background process and thus it will run asynchronously

  9. #9
    SitePoint Evangelist
    Join Date
    Mar 2005
    Posts
    423
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by oeyvind View Post
    As a workaround one could call a php script with exec('php cron.php &'). This will (with the '&') make the process a background process and thus it will run asynchronously
    I never knew that about the ampersand. Another nice tip!

  10. #10
    SitePoint Guru
    Join Date
    Oct 2006
    Location
    Queensland, Australia
    Posts
    852
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by skinny monkey View Post
    That's quite a nice example, but there's a wee bug in that code.
    That's what happens when you don't unit test :P. Thanks for spotting that out. Those sorts of bugs can live on for a long time without being noticeable (only really affecting performance).

    Quote Originally Posted by oeyvind View Post
    Some jobs might take a long time, so if you don't detach it from the current request, one of the site's users is going to have to wait for a long time for the cron to finish it's work, and he might cancel the request or it might time out.
    Yes, true. Thanks for pointing that out.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •