RE: [PHP] Sessions vs Cookies?

From: Date: Fri, 22 Jun 2001 00:45:00 +0000
Subject: RE: [PHP] Sessions vs Cookies?
Groups: php.general 
Request: Send a blank email to php-general+get-54824@lists.php.net to get a copy of this message
> I am about to write a new admin system for a website I do and > it will have many different logins. I was wondering overall which > most of you thought would be better for such a thing? Wants really > a pro about sessions over cookies? If it's for an admin section, then you may as well use cookies. If the client doesn't want to use cookies they can't use their admin interface. :) I doubt they would have privacy issues with themselves anyway. If you're going to use cookies, hopefully you'll have a database system available (you said you'd have lots of different logins). So, create a session table: ID int username text password text (if required, maybe you won't need it again) logintime int expirytime int magickey text Generate a magic key as such: <? $randomseed = intval(ereg_replace("[^0-9]", "", substr(Date("U").microtime(), 4, 10))); srand($randomseed); $newid = rand(11111, 99999); $magickey = md5($newid.$REMOTE_ADDR.time()); ?> This should give you sufficient entropy as to make the magickey unguessable (except by sheer fluke). Send the magic key as the cookie and log it in the table (sessiontime = session time in seconds): >>> INSERT INTO sessions (username, (password if needed,) logintime, expirytime, magickey) VALUES ('$uname', ('$pass',) Date("U"), Date("U")+$sessiontime, '$magickey') Every page in the admin area should check the cookie: >>> SELECT * FROM sessions WHERE magickey = '$yourcookievalue' >>> Ensure that epxirytime is not less than date("U") If those checks fail, redirect them to the login page and Exit(). If the user logs out and you're storing passwords, ensure you delete the password with an UPDATE command or else someone breaking into your system will have just found all your admin passwords. You might want to run a script on a crontab to do that as well. As a slightly more kludgy alternative, take the md5() of the last modification time of a file somewhere: <? $lastmod = filemtime("/path/to/your/admin/page/index.php"); $checkvalue = md5($lastmod); ?> And set $checkvalue as your cookie. Every subsequent page should then perform the same check and if it fails, redirect as above and Exit(). Hope this helps somewhat. Jason -- Jason Murray jasonm@melbourneit.com.au Web Developer, Melbourne IT "What'll Scorpy use wormhole technology for?" 'Faster pizza delivery.'

« previous php.general (#54824) next »