Cookies in PHP

You can set cookies in PHP, thus avoiding JavaScript. However, setting them from the server side has a limitation which arises from the way servers set cookies.

Servers set cookies by sending some protocol traffic before the page content (the XHTML or XML). This means that you have to be careful not emit (output) any XHTML before setting cookies. If you do, the cookies simply won't get set.

Here is an example of cookie setting:

setcookie ("login", $login);

The "login" is the cookie name and $login is a variable containing the new cookie contents.

Redirection

Servers sometimes send a different page to the one the user requested. This is known as "redirection" and has the same limitation as cookie setting -- it can only be done if no content has been sent.

Here is an example of redirection:

Header( 'Location: getStuffed.html');
exit;

The Header function does the redirection. The exit statement causes the script to stop and produce no more output.

PHP scripts usually contain both redirection and cookie setting, if they contain either. For example, you might redirect users to a login page and back.

Skeleton Login Pages

Here are PHP skeletons of two schemes for handling login cookies. Have a play with them and examine the code. Which is simpler? Which is the more powerful? Why?

Scheme One

Right click here to play with scheme one in a new window.

Here are the sources (right click for new windows):

Scheme Two

Right click here to play with scheme two in a new window.

Here are the sources (right click for new windows):

Include the Code

Scheme two in particular lends itself to being implemented via include files so that you don't have to keep putting the same code in many PHP scripts. Everything before the page proper could be in an include file called, say, login.php.


Written by Peter Scott

Valid XHTML 1.0! Valid CSS!