WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search


Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder



Go Back Add a Comment Send this Article to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES SUBMIT AN ARTICLE PRINT
Title : Beginners Guide to PHP - Introduction to cookies
Categories : Beginner Guides, Cookies, To PHP, PHP
Rafi Ton
Rafi Ton
Date : 2000-02-23
Grade : 0 of 5 (graded 0 times)
Viewed : 54925
Search : More Articles by Rafi Ton
Action : Grade This Article
Tools : My Favotite Articles


Submit your own code examples 
 


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&lt;/title>
&lt;/head>
<body>
<p>Hello $FirstName $LastName, this is your visit number: $count&lt;/p>
<p>Your email address is: $email&lt;/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&lt;/title>
&lt;/head>
<body>
<a href=\"reg.php3\">Click Here for Site Registration&lt;/a>
&lt;/body>
&lt;/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&lt;/title>
&lt;/head>
<body>
<p>Hello $FirstName $LastName, this is your visit number: $count&lt;/p>
<p>Your email address is: $email&lt;/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&lt;/title>
&lt;/head>
<body>
<a href=\"reg.php3\">Click Here for Site Registration&lt;/a>
&lt;/body>
&lt;/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&lt;/title>
&lt;/head>

<body bgcolor=#ffffff>
<h1>Registering the site&lt;/h1>

<form method="post" action="reg1.php3">
<table width=90% align=center>
<tr><td>User Name:&lt;/td><td><input type=text name='FirstName' size=20
maxlength=20>&lt;/td>&lt;/tr>
<tr><td>Last Name:&lt;/td><td><input type=text name='LastName' size=40
maxlength=40>&lt;/td>&lt;/tr>
<tr><td>email addrress:&lt;/td><td><input type=text name='email' size=40
maxlength=40>&lt;/td>&lt;/tr>
<tr><td>&lt;/td><td><input type=submit value="Click to Register">&lt;/td>&lt;/tr>
&lt;/table>
&lt;/form>
&lt;/body>
&lt;/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.&lt;/p>"
;
echo
"<p><a href=\"index.php3\">Back to Main Page&lt;/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.&lt;/p>";
echo "<p><a href=\"index.php3\">Back to Main Page&lt;/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.&lt;/p>";
echo "<p><a href=\"index.php3\">Back to Main Page&lt;/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.

Have fun with Cookies.
Rafi Ton, [email protected]









Counting - Creating a more sophisticated GIF based counter using PHP and MySQL
Categories : Beginner Guides, MySQL, PHP, To PHP, To MySQL
PHP 101 Part 10 of 15 : A Session In The Cookie Jar
Categories : PHP, Beginner Guides, Cookies, Sessions
Who's Linking?
Categories : PHP, Beginner Guides, To PHP
Grabb'n and Pars'n
Categories : Beginner Guides, PHP, To PHP
Jump Start to Easy URLs
Categories : PHP, Beginner Guides, MySQL, File System, To PHP
Beginners guide to PHP and MySQL - Creating a simple guest book
Categories : Beginner Guides, To PHP, To MySQL, PHP, MySQL
Counting - Creating a simple counter
Categories : PHP, MySQL, Beginner Guides, To PHP, To MySQL
Counting - Creating a GIF based counter using PHP and MySQL
Categories : Beginner Guides, PHP, To PHP, To MySQL, MySQL
How TO Install PHP, Apache and MySQL on Linux or Unix
Categories : PHP, MySQL, Apache, Installation, Beginner Guides
Beginners guide to PHP and MySQL
Categories : PHP, Beginner Guides, Databases, MySQL, Installation
PHP 101 Part 15 of 15 : No News Is Good News
Categories : PHP, Beginner Guides, Content Management
Building a Counter
Categories : PHP, Cookies
PHP 101 Part 5 of 15 : Rank And File
Categories : PHP, Beginner Guides, Filesystem
Using If Else Statements
Categories : PHP, Beginner Guides
PHP and OOP
Categories : PHP, Object Oriented, Beginner Guides
nick wrote : 31
Hi,

i am having a problem with my cookie script: using
setcookie(), the cookie does not seem to get saved
anywhere on the users` hard disk ?! I tried on
several machines using ie5 and can`t seem to find
the cookie in the "cookies" directory. Plus my script
creates a new cookie every time i reopen explorer
(tho not when i refresh it) so i guess the cookie isn`t
getting writte. My script is:

if (isset($cookiename))
{ //Begin instructions for existing Cookie
$info = explode("&", $cookiename);

then update counter; then update info in db;
else create new cookie using setcookie after having
gotten info off the database:

#insert these variables into database
mysql_connect("", "", ") or die ("Problem connecting
to DataBase in creating new cookie");
$query = "insert into cookies1 values (`predefined
variables except for an auto_increment primary key
called ID, which is set to null`)";
$result = mysql_db_query("dbname", $query) or die
("Problems.... ");

#i then redo a search on the db lookin for #these
predefined values to find out what #number mysql
has assigned to $ID
mysql_connect(``, ``, ``) or die ("Problem ");
$query = "select * from tablename where
variable1=`$variable1` AND count=`$count`";
$result = mysql_db_query("dbname", $query) or die
("Problems.... ");
$r=mysql_fetch_array($result);
$ID=$r["ID"];

#set these variables into cookie
$CookieString=$1.`&`.$2.`&`.$3.`&`.$ID;
setcookie ("cookiename",$CookieString, time()
+99999999999, "/", ".mysite.com", 0);


any ideas why this doesn`t work ???

cheers, nick
Ivo Bons wrote : 39
I`m having the same problem as Nick describes. There
isn`t any cookie stored on my HD when I use IE 5.
Everthing works fine under Netscape 4.7. Any ideas??

Greetz,

Ivo
Boaz Yahav wrote : 40
Try setting the cookie like this :

setcookie ("cookiename",$CookieString, time() +3600,
"/", ".mysite.com", 0);




wrote : 140
This one realy works:

setcookie (`cookiename`,"`$CookieString`", time()
+3600, ``,``, 0);
Jonas Tillberg wrote : 141
Perfect!
Anonymous wrote : 150
Hi,

The script sets the cookie ok. But, when I come back to
the page it displays this error.

Warning: Cannot add header information - headers
already sent by (output started at
C:\httpd\HTDOCS\cookie\index.php:2) in
C:\httpd\HTDOCS\cookie\index.php on line 11

Then prints out the correct cokkie information as I
desire.

I asume this is hapening as stated here?

<<<<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. >>>

What have I done wrong? I followed the script just as
you stated.

here is the script:


<? 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
?>

Thanks for any help you can provide. Even though this
is not working for me yet it is certainly the best cookie
artrical for people like me who know nothing about
cookies, except sometimes you have to use them to
make life easy!.

Thanks.

Anonymous wrote : 176
Note: Do not send output (including spaces, blank lines,
HTML and newlines, meaning, \n, \r, etc.) before using
the header() function. Doing so will result in a parse
error when you attempt to access your script.
Anonymous wrote : 197
i am having trouble getting this to work, i am getting
the following error:
Warning: Supplied argument is not a valid MySQL result
resource
in /home/newearth/public_html/testing/reg1.php3 on
line 9

Warning: Cannot add header information - headers
already sent by (output started
at /home/newearth/public_html/testing/reg1.php3:9)
in /home/newearth/public_html/testing/reg1.php3 on
line 24
Thank you for registering.

is there something wrong with my table in MySQL? iset
it up using phpMyAdmin

any help would be appreciated
thanks
Anonymous wrote : 209
well see this

<?
$zed = 123;
if(setcookie ("cookiename",$zed, time()+3600,"","", 0))
{echo "cool";}
echo $cookiename;
echo "/".$zed;
?>

This script is in www.webbit.f2s.com/cookie.php

it doesn`t seem to work. Could it be f2s ?

Im using le 5.5
Anonymous wrote : 268
you are geeting the header error because there some
output before the cookie is set. to resolve this add the
call
ob_start();
at the begining of the program (after the <?php
command) and add the call
ob_end_flush();
at the end of the program (before the ?> command).

Hopefully that should help. Check the php manual for
information on exactly how these functions work.
Daniel Skates wrote : 356
Hey,
Great tutorial.
However, I have a few questions.
1) The code sections use &alt; or something for the < sign.
2) When I use this code, it tells me to register. I enter
the info and click the button to find that I always get the
following message:
`Sorry, some information is missing. Please go back and add
all the information`
Any ideas?
The coding is exactly the same as the coding on your
article.

Thanks
d.
rain b wrote : 358
I got little problem concerning this tutorial.
Everything seems to work but when I have registered I
return to the main page. There should be
text...hello `yourname` this is your visit nr `x` etc
but the page is just blank- no text at all. When I view the
source for the page then there`s eveything exists. Any
suggestions?