Beginners Guide to PHP - Introduction to cookies

advertisement
Beginners Guide to PHP - Introduction to cookies
In this tutorial we will learn how to handle cookies with PHP. Like my previous articles, I will try to keep things as
simple as possible and explain the basics as well as some practical implementations of cookies.
What are cookies and why do we need them?
Cookie is a piece of information generated by the web server and stored in the clients’ computer. Cookies are embedded
in the HTML information flowing between the server and the client side (the browser) generally allowing server side
customization of information. Cookies may be utilized for various tasks like: personalization of web pages, counters,
store data while browsing the site, store statistics etc.
Cookies and PHP
Using cookies with PHP is pretty easy. One can set a cookie using the SetCookie function. Cookies are part of the
HTTP header, so the SetCookie function must be called before any output is sent to the browser. This is the same
restriction as for the Header function. Any cookies sent to you from the client will automatically be turned into a PHP
variable. PHP takes the header and parses it, extracts the cookie names and turns them into variables. So, if you did a
SetCookie("MyCookie","Rafi Ton"); then PHP will automatically create a variable called $MyCookie with a value of
"Rafi Ton".
Let's review the SetCookie syntax:
setcookie(string CookieName, string CookieValue, int CookieExpireTime, path, domain, int secure);
PATH: directory under web server this cookie is for. Default is to the directory of the requested page.
DOMAIN: The domain name this cookie can be used under. Default is the domain of the requested page. The domain
must have two '.' in it, so if you decide to specify you're top level domain, you must use ".mydomain.com".
SECURE: If set to '1', indicates that the cookie should only be transmitted over a secure HTTPS connection.
Please note that cookies will not become visible until the next loading of a page that the cookie should be visible for.
Multiple calls to SetCookie in the same script will be performed in the reverse order. If you are trying to delete
one cookie before inserting another you should put the insert before the delete.
Down to business:
Let's say we want to enable registration to a site and to automatically recognize known users and to send them a
message while unknown users will be presented with a message asking them to register. We will create a small
database with the following information: First Name, Last Name, email address and a visit counter.
Assuming you've read my Beginners Guide to PHP/MySQL, we will create the following table:
mysql> create database users;
Query OK, 1 row affected (0.06 sec)
mysql> use users;
Database changed
mysql> create table info (FirstName varchar(20), LastName varchar(40),
email varchar(40), count varchar(3));
Query OK, 0 rows affected (0.05 sec)
Ok, now we have our table with the columns we need. Let's create a PHP page to check the cookies and compare them
to the database:
Index.php3
<? if (isset($Example)) { //Begin instructions for existing Cookie
$info = explode("&", $Example);
$FirstName=$info[0];
$LastName=$info[1];
$email=$info[2];
$count=$info[3];
$count++;
$CookieString=$FirstName.'&'.$LastName.'&'.$email.'&'.$count;
SetCookie ("Example",$CookieString, time()+3600); //setting new cookie
echo" <html>
<title>Rafi's Cookie example</title>
</head>
<body>
<p>Hello $FirstName $LastName, this is your visit number: $count</p>
<p>Your email address is: $email</p>
<body>
<html>";
mysql_connect() or die ("Problem connecting to DataBase"); //update DB
$query = "update info set count=$count where FirstName='$FirstName' and
LastName='$LastName' and email='$email'";
$result = mysql_db_query("users", $query) or die ("Problems .... ");
} //End Existing cookie instructions
else { //Begin inctructions for no Cookie
echo "<html>
<head>
<Title>Rafi's Cookie example</title>
</head>
<body>
<a href=\"reg.php3\">Click Here for Site Registration</a>
</body>
</html>";
} //End No Cookie instructions
?>
Please note that if you are using a remote MySQL server or a unix one you should use:
mysql_connect ("server","username","password") or die ("Problem connecting to DataBase");
We want to check whether a cookie with the name we specified before was transferred in the HTML header. Remember
that PHP transforms any recognized cookie into a variable with corresponding name, so we are able to check for a
variable named 'Example':
<? if (isset($Example)) { //Begin instructions for existing Cookie
...
} else {
...
}
If the cookie exists we want to increase the counter number and printout the users' information and if the cookie does
not exist we want the user to register first.
If the cookie exists we will perform the following instructions:
<? if (isset($Example)) { //Begin instructions for existing Cookie
$info = explode("&", $Example); //split the string to variables
$FirstName=$info[0];
$LastName=$info[1];
$email=$info[2];
$count=$info[3];
$count++;
$CookieString=$FirstName.'&'.$LastName.'&'.$email.'&'.$count;
SetCookie ("Example",$CookieString, time()+3600); //setting a new cookie
echo" <html>
<title>Rafi's Cookie example</title>
</head>
<body>
<p>Hello $FirstName $LastName, this is your visit number: $count</p>
<p>Your email address is: $email</p>
<body>
<html>";
mysql_connect() or die ("Problem connecting to DataBase"); //update DB
$query = "update info set count=$count where FirstName='$FirstName' and
LastName='$LastName' and email='$email'";
$result = mysql_db_query("users", $query) or die ("Problems .... ");
} //End Existing cookie instructions
The above script has 3 major parts: First it takes the cookie value and splits it into variables using the explode functions,
increases the counter and sets a new cookie. Then it prints the users’ information in HTML and finally it updates the
database with the new counter value.
Few words about the explode functions: explode returns an array of strings containing the elements separated by a
separator. In this tutorial the cookie value string holds the users' first name, last name, email and a counter separated by
the ‘&’ sign. So, if I want to separate the cookie value string into elements I use the following syntax:
$info = explode("&", $Example);
The function returns an array named info which holds the elements in $info[0], $info[1] etc. Now I can use the cookie
information and manipulate it (for convenience purposes I assigned the values to named variables). Next, I
increase the cookie counter using:
$count++;
and create a new cookie with the updated information:
$CookieString=$FirstName.'&'.$LastName.'&'.$email.'&'.$count;
SetCookie ("Example",$CookieString, time()+3600); //setting a new cookie
I created a new $CookieString with all the information and separated by '&'. Notice that I used a '.' to combine the
elements into a large string.
Next, I can sent the information to the browser (please refer to the Beginners Guide to PHP/MySQL for further
information).
Finally, I want to update the MySQL database with the new counter using the MySQL update function (also explained
in more details at the Beginners Guide to PHP/MySQL):
mysql_connect() or die ("Problem connecting to DataBase"); //update DB
$query = "update info set count=$count where FirstName='$FirstName' and
LastName='$LastName' and email='$email'";
$result = mysql_db_query("users", $query) or die ("Problems .... ");
If the cookie does not exist the following instructions will be executed:
else { //Begin inctructions for no Cookie
echo "<html>
<head>
<Title>Rafi's Cookie example</title>
</head>
<body>
<a href=\"reg.php3\">Click Here for Site Registration</a>
</body>
</html>";
} //End No Cookie instructions
This set of instructions simply prints out a link to the registration page named reg.php3, which is basically a form with
the corresponding fields.
reg.php3:
<html>
<head><title>Registering the Site</title>
</head>
<body bgcolor=#ffffff>
<h1>Registering the site</h1>
<form method="post" action="reg1.php3">
<table width=90% align=center>
<tr><td>User Name:</td><td><input type=text name='FirstName' size=20
maxlength=20></td></tr>
<tr><td>Last Name:</td><td><input type=text name='LastName' size=40
maxlength=40></td></tr>
<tr><td>email addrress:</td><td><input type=text name='email' size=40
maxlength=40></td></tr>
<tr><td></td><td><input type=submit value="Click to Register"></td></tr>
</table>
</form>
</body>
</html>
Please refer to the Beginners Guide to PHP/MySQL for further information forms and PHP.
After all the information was filled the form calls another PHP script which analyzes the information:
reg1.php3:
<?
if ($FirstName and $LastName and $email)
{
mysql_connect() or die ("Problem connecting to DataBase");
$query="select * from info where FirstName='$FirstName' and
LastName='$LastName' and email='$email'";
$result = mysql_db_query("users", $query);
$r=mysql_fetch_array($result);
$count=$r["count"];
if (isset($count)) {
$CookieString=$FirstName.'&'.$LastName.'&'.$email.'&'.$count;
SetCookie ("Example",$CookieString, time()+3600);
echo "<p>user $FirstName $LastName already exists. Using the existing
info.</p>";
echo "<p><a href=\"index.php3\">Back to Main Page</a>";
} else {
$count = '1';
$query = "insert into info values
('$FirstName','$LastName','$email','$count')";
$result = mysql_db_query("users", $query);
$CookieString=$FirstName.'&'.$LastName.'&'.$email.'&'.$count;
SetCookie ("Example",$CookieString, time()+3600);
echo "Thank you for registering.<br>";
}
} else { echo "Sorry, some information is missing. Please go back and add all
the information"; }
?>
First we want to check whether all the information was typed in, and if not send back the user to enter the necessary
data:
<?
if ($FirstName and $LastName and $email)
{
...
} else { echo "Sorry, some information is missing. Please go back and add all
the information"; }
?>
Assuming all the information was entered the following instruction set will be executed:
mysql_connect() or die ("Problem connecting to DataBase");
$query="select * from info where FirstName='$FirstName' and
LastName='$LastName' and email='$email'";
$result = mysql_db_query("users", $query);
$r=mysql_fetch_array($result);
$count=$r["count"];
if (isset($count)) {
$count++;
$CookieString=$FirstName.'&'.$LastName.'&'.$email.'&'.$count;
SetCookie ("Example",$CookieString, time()+3600);
echo "<p>user $FirstName $LastName already exists. Using the existing
info.</p>";
echo "<p><a href=\"index.php3\">Back to Main Page</a>";
} else {
$count = '1'; //new visitor - set counter to 1.
$query = "insert into info values
('$FirstName','$LastName','$email','$count')";
$result = mysql_db_query("users", $query);
$CookieString=$FirstName.'&'.$LastName.'&'.$email.'&'.$count;
SetCookie ("Example",$CookieString, time()+3600);
echo "Thank you for registering.<br>";
This script does few things: it checks whether the database has such a user (if, let’s say, the cookie was deleted etc.) and
if so, it assigns the old information and creates a new cookie with the current information and if there is no entry on the
database with identical user it creates a new entry at the database and a new cookie.
First we will try to retrieve from the database an entry with the user details transferred from the form:
mysql_connect() or die ("Problem connecting to DataBase");
$query="select * from info where FirstName='$FirstName' and
LastName='$LastName' and email='$email'";
$result = mysql_db_query("users", $query);
$r=mysql_fetch_array($result);
$count=$r["count"];
Now we can check whether we have an active counter for the specified user using the isset() function:
if (isset($count)) {
...
} else {
...
}
Now, if we have an active counter to the user all we have to do is to assign the information from the MySQL database
to the user, increase the counter and create a new cookie:
$count++; //increase counter
$CookieString=$FirstName.'&'.$LastName.'&'.$email.'&'.$count;
SetCookie ("Example",$CookieString, time()+3600);
echo "<p>user $FirstName $LastName already exists. Using the existing info.</p>";
echo "<p><a href=\"index.php3\">Back to Main Page</a>";
If we don't have an active counter on the MySQL database then we have to create an entry on the database using the
MySQL insert function and set a cookie:
$count = '1'; //new visitor - set counter to 1.
$query = "insert into info values ('$FirstName','$LastName','$email','$count')";
$result = mysql_db_query("users", $query);
$CookieString=$FirstName.'&'.$LastName.'&'.$email.'&'.$count;
SetCookie ("Example",$CookieString, time()+3600);
echo "Thank you for registering.<br>";
Please notice that whenever I need to set a cookie, the setcookie() comes before any output is sent to the browser
otherwise you will get an error stating that the header is already set.
Download