In the course of developing highly interactive web sites it is necessary to deal with large amount of data flow between client browswer and web server. It is quite cumbersome handling such large amount of data using hidden fiels in HTML forms. This problem can be overcomed by using HTTP cookies. HTTP cookies are the bunch of data/text sent by the server to the web browswer. Web browser store this data locally and send back to the server each time it accesses the server before it expires. Note that now a days Most browsers allow users choice to accept cookies or not, sometime rejection causes web site to not work properly.
setcookie() function.
This function in PHP Language is used to work with HTTP cookies. setcookie() defines a cookie to be sent along with the rest of the HTTP headers. This must be called before sending any output to the browser because cookies are part of the HTTP header. On successful it will return TRUE. But this does not mean that client browser has ccepted cookie.
setcookie() syntax.
bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]])
- name: This argument sets the name of the cookie.
for example setcookie(’mycookie’, …) will set mycookie and is called $_COOKIE['mycookie'] at server side. - value: This will set the value of the cookie. Since this values is stored on the client browser extra care must be taken that it does not store some secure information e.g passwords. The values is accessed by $_COOKIE['mycookie'] at the web server.
- expire: Sets the expire time of cookie. It is Unix timestamp so generally it is used with time() function. For example time()+60*30. This will set the cookie to expire in 30 minutes. If not set the cookie is not persistent and will expire when the browser closes.
- path: The path of cookies are used to organise cookies based on the path at web server. If set to ‘/’ this cookie is availabe to all directories. If set to ‘/dir1/’ this cookie is availabe to dir1 only and all sub directories of /dir1 i.e /dir1/sub1. Note that the default value is the current directory so if the current directory is ‘/dir1/’ and you want to set it for all directories it must be ‘/’
- domain: This argument will decide in which domain cookie is accesible. Value ‘www.mydomin.com’
makes it accesible to www sub-domain only. To make it accessible to all subdomains of mydomin.com a value
‘.mydomin.com’ must be set. - secure: Value 1 indicates the cookie must be used on secure (https) connection. Default value is 0.
setcookie() Examples.
setcookie(’mycookie’, ‘Test mycookie’); This will set ‘mycookie’ with value ‘Test mycookie’ will expire when browser closes.
setcookie(’mycookie’, ‘Test mycookie’, time()+3600*24); This will expire in 1 day.
setcookie(’mycookie’, ‘Test mycookie’, time()+3600*24, “/dir1/”); Available to /dir1 directory and all subdirectories under it.
Accessing cookie values at server.
At server in PHP script, cookies sent from the client browser will be turned into PHP variables. After PHP 4.1.0 the global array variable $_COOKIE is set for cookies from the client. $HTTP_COOKIE_VARS is also present which is availabe before PHP 4.1.0. See example below.
echo $_COOKIE["mycookie"]; This will output “Test mycookie” in our example.
Testing cookie.
On successful return of setcookie() does not mean that client browser has accepted the cookie or cookie is set successfully. It must be checked on next loading of the page if a cookie was successfully set or not. This can be done by using PHP function print_r($_COOKIE) function. This will show weather the cookie is set or not.
Deleting a cookie.
Cookies can be deleted by setting its value to “” and all other parameters must be the same as they were set at the time of sending the cookie. We must ensure that the expiration date is in the past when deleting the cookie. See examples below.
setcookie (”mycookie”, “”, time() – 3600);
setcookie (”mycookie”, “”, time() – 3600, “/dir1/”);
Multiple cookies.
Multiple cookies can be set using following.
setcookie(’mycookie1′, ‘Test mycookie1′);
setcookie(’mycookie2′, ‘Test mycookie2′);
setcookie(’mycookie3′, ‘Test mycookie3′);
setcookie(’mycookie4′, ‘Test mycookie4′);
And can be accessed by following.
echo $_COOKIE["mycookie1"];
echo $_COOKIE["mycookie2"];
echo $_COOKIE["mycookie3"];
echo $_COOKIE["mycookie4"];
Cookies Array.
We can use PHP array in cookies. see example below
setcookie(”mycookie[0]“, “value1″);
setcookie(”mycookie[1]“, “value2″);
setcookie(”mycookie1['one']“, “value11″);
setcookie(”mycookie1['five']“, “value15″);
This is similar of setting many cookies but the values are placed in the PHP array at the
receing PHP script.
foreach ($_COOKIE['mycookie'] as $key => $value) {
echo “$key:$value “;
}
This will print 0:value1 1:value2
And
foreach ($_COOKIE['mycookie1'] as $key => $value) {
echo “$key:$value “;
}
Will print print one:value11 five:value15
April 9, 2007 at 6:05 am |
nice page
i also am into PHP and MySQL. I must admit,however, that I still am a beginner. I’m actually trying to figure out how I can set cookies to mysql_connect so that I won’t have to write the connection code to each PHP page. Do you have any idea how to do it?
$user = “admin”;
$pass = “pass”;
$db = “getta”;
$tb = “members”;
$link = mysql_connect(”localhost”, $user, $pass) or die (mysql_error());
mysql_select_db($db) or die (mysql_error());
Do you know how to use cookies to this code? I tried to put the code below in the Body of my HTML, but it didnt work
I only encountered this error message:
Access denied for user ‘ODBC’@'localhost’ (using password: NO)
Maybe you can help…
April 10, 2007 at 11:51 am |
You can write your connection code in one file and just include it in other files. You don’t need cookie for it.
April 22, 2007 at 6:50 pm |
Thanks, always good posts on your blog!
April 4, 2008 at 6:02 am |
knowled
November 15, 2008 at 4:23 pm |
Nice Article with example
November 15, 2008 at 4:23 pm |
This help to all php learner
December 7, 2008 at 5:25 pm |
I was actually looking around for anything on storing arrays in cookies. Well it was new for me to learn that the arrays are stored in the receiving php script. Explains why i couldn’t find the cookie when i stored arrays in them.
Another thing that I have been pondering over for sometime now, is how do we destroy an array stored in a cookie. have tried most of the common methods of setting the expiry in the past, setting to null, unset cookie… etc. but i can’t seemed to find a way to destroy the cookie holding the array except when the window is closed. Would love to hear any comment on this…
Warmest Regards…
December 23, 2008 at 11:31 pm |
Very nice article! Was looking for a while for something this simple and to the point. Much regards.
January 29, 2009 at 10:49 am |
php is the very interesting language for web page building. you have here explain php cookie in easiest way. every think is explain nicely. it is easy to understand.
March 28, 2009 at 4:26 am |
when i use email addresses the content adviser tells me i can’t view my page ,whats goung on?no one will tell what i’m ddoing wrong i am just trying to learn!
May 26, 2009 at 1:20 pm |
Great read, thanks
June 6, 2009 at 8:47 am |
Interesting article)
June 9, 2009 at 7:14 pm |
Hey I was just wondering when you put up go to my website and a cookie will pop up and you have to type your name. well if you go to a diffrent link then go back to the home page the cookie will pop up and agian etc.. is there any way so the cookie will only pop up when you just enter the site
June 11, 2009 at 4:05 am |
Nice article…. helped a lot to understand the concept….
Thanks,
Meenal A. Mukadam