Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: cookie based sessions

Tags:

does any body have any info/links as to how to integrate a cookie based session system? i've used file/mysql, and am currently using memcached. i wanted to play with apc sessions, but thought i'd give a go at cookies, only i don't know much about it.

i imagine i'd have to write my own session handler class?

like image 210
onassar Avatar asked Jan 11 '10 19:01

onassar


1 Answers

In PHP session data is usually stored in a file. The only thing stored in the cookie is a session identifier. When sessions are enabled and a valid session cookie is found, PHP loads the users session data from the file into a super global called funnily enough SESSION.

Basic sessions are started using session_start(); called before any text is sent to the browser. then items are added to or removed from the session object using simple array indexing eg.

$_SESSION['favcolour'] = 'blue'; 

later...

$favcolour = $_SESSION['favcolour'];

basic cookie only sessions (no local storage) can be created with a call to

 set_cookie('favcolour','blue'[,other params]);

before any text is sent to the browser, then retrieved from the cookie superglobal

$favcolour = $_COOKIE['favcolour'];

you don't need to call session_start() if doing cookie only sessions.

the optional [,other params] are more advanced and can be read about here http://www.php.net/manual/en/function.setcookie.php

Sessions can become a very complex discussion, I'd suggest doing some light work in them and then expand your knowledge.

DC

all you ever wanted to know about PHP sessions

http://www.php.net/manual/en/book.session.php

DC

To reuse PHP's session handling code you will need to add a write handler using session_set_save_handler and then do exactly nothing in that handler. That's because its called after the output to the browser is closed therefore you cannot send anything to the browser.

Before writing non header data to the browser use the set_cookie functions and store the contents of the $_SESSION array (after serialising and encrypting) into a cookie. when the applications start you can read the cookie unserialise it and put it into the $_SESSION array.

That's a quick hint at what to do as I have never done it, I prefer to write all my own cookie code. There may be some gotcha's but its not hard a few tests should find any gotcha's.

DC

like image 107
DeveloperChris Avatar answered Oct 12 '22 01:10

DeveloperChris