Writing And Reading Multiple Cookies

A tutorial on how to set multiple cookies which can be used to store information about a certain user.

In category php.

Posted by Joseph Skidmore on 11.09.05.

Following on from my first tutorial of introduction to cookies, this tutorial shows you how to set multiple cookies. Setting multiple cookies can come in handy if you wish to store more than one piece of information about a user, such as Username & Password for example.

We will start off with our form that will allow the user to input the data we want to store.

Index.php

<form method="post" name="cookie" action="setcookies.php">

<p>First Name : <input type="text" name="firstname" /></p>
<p>Surname : <input type="text" name="surname" /></p>

<p><input type="submit" name="submit" value="Submit" /></p>
</form>

As you can see it is a very basic form. 2 input boxes for first name and surname which on submit takes the form to setcookies.php for processing.

setcookies.php

<?php

$firstname = $_POST['firstname'];        
// Gives the inputted username a variable name 'firstname'

$surname = $_POST['surname'];        
// Gives the inputted password a variable name 'surname'

$time = time();                
// Gets the Current Server Time


setcookie("Joe2Torials[firstname]", $firstname, $time + 3600);    
// Set a cookie storing the firstname

setcookie("Joe2Torials[surname]", $surname, $time + 3600);    
// Set a cookie storing the surname

/*
    Both  cookies  are  set to  expire in  1 hour,  the variable
    $time grabs the current server time and then adds 3600
    adds  one day of  time to it. 60 * 60 = 3600 (60 seconds
    in  a  minute  *  60 minutes in an hour)  = 3600 seconds.
    After the  code has run  and the  cookies  have been set
    the code  then forwards the  user to the  following page:
*/

header('Location: http://www.domain.com/readcookies.php');
exit();

?>

This code grabs the inputted data from the form (firstname and surname) and stores them in variables. The variables are then set inside cookies with the names [firstname] and [surname] (notice the cookie is actually named Joe2Torials) all will come clear about this in the readcookies.php page. After the code has run it automatically forwards the user to readcookies.php.

<p>Welcome to the admin section. Your firstname and surname is:</p>

<ul>
<?php

$firstname = $_COOKIE['Joe2Torials']['firstname'];        
// Read the cookie with the name 'firstname'

$surname = $_COOKIE['Joe2Torials']['surname'];        
// Read the cookie with the name 'surname'

echo '<li>'.$firstname.'</li>'; // Echo the firstname
echo '<li>'.$surname.'</li>';  // Echo the surname

?>

</ul>

Here we grab the cookies with the names firstname and surname and give them variables, then we display them on screen, simple huh?

Click here to view my writing and reading cookies example page.

Page generated in 0.0016 seconds.

Whatcounter Free Invisible Stats CounterFree invisible hit counter