PHP Cookies Tutorial And PHP Cookies Examples

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

44 Responses to PHP Cookies Tutorial And PHP Cookies Examples

  1. evanonsense says:

    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…

    • chani says:

      nice…..explained in detail…

    • Hritik says:

      It means that, ur username -admin is wronge on localhost.
      If u r using wampserver, then its default mysql connect username is “root” and it has no password.
      So in wampserver use-
      mysql_connect(“localhost”,”root”);

    • Roger Lunsdtröm says:

      Someone said “localhost” was incorrect, but it is not. Since php is a serverside script, the access to your mysql server is done from your own computer, hence it works perfectly. Since I don’t need any javascripts to access the server I have set mysql to refuse all other addresses besides 127.0.0.1.. To answer your question: You don’t WANT this information in a cookie. a cookie is stored on the users computer and if he knows a bit of computing he will be ablet to get your mysql password and that will leave your program vulnurable for a hacking attempt.

      Workaround: Create a textfile somewhere unaccessable on your server (either in a passwordprotected folder, or in a folder that isn’t even part of your html structure) and in that you write the access code for your server, including passwords, and other reusable code that you want all pages to access. Then you simply use the php directive “include” in the beginning of all .php pages that need to use that code. (again; as php is being run on serverside it can access your file structure directly and won’t use the server programs security settings.. this makes it possible to utilize a file that isn’t accessable from the outside, thus increase security, but you also have to be aware of the risc of code infusion..)

  2. anonymous says:

    You can write your connection code in one file and just include it in other files. You don’t need cookie for it.

  3. Desktopjunk says:

    Thanks, always good posts on your blog!

  4. Praveen says:

    Nice Article with example

  5. Praveen says:

    This help to all php learner

  6. Ananth says:

    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…

  7. dPrime says:

    Very nice article! Was looking for a while for something this simple and to the point. Much regards.

  8. harish says:

    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.

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

  10. Stuart says:

    Great read, thanks

  11. Darkhan says:

    Interesting article)

  12. chase says:

    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

  13. Meenal A. Mukadam says:

    Nice article…. helped a lot to understand the concept….

    Thanks,

    Meenal A. Mukadam

  14. sam says:

    yow. . .im a newbie to php. im just wondering how to set cookie for, say for example user id stored in a database. when i logged in, yes the information of the user was displayed in the home page but when i visit other pages and return to home, the page was cleanly blank. can you please help me figure this one out? ? ? if you don’t mind, email some comments or it would be great it there will be snippets. thanks in advance

  15. I don’t understand, because I don’t know what a “client browswer” is…

  16. Basit says:

    all my cookies work great on subdomain, but if subdomain has “_” in it, then cookie dont get read at all and dont get right at all eaither. following are my tested result, which will self explain

    justlife.demo.com *** works fine ***
    just-life.demo.com *** works fine ***
    just-.demo.com *** works fine ***

    just_.demo.com *** DONT works fine ***
    just_life.demo.com *** DONT works fine ***

    domain that dont work, the cookies for them shows completely emtpy and you cant right or read from that sub-domains..

    this problem is only in IE.

    firefox and chrome works fine, they dont have this error.

    any solution for this?

  17. Lonestar Jack says:

    I was using $_SESSION variables until Vista came along and ruined that logic.
    Thanks for the tutorial as I have now converted to passing several variables with cookies.

  18. […] PHP Cookie Tutorials AKPC_IDS += "139758,"; […]

  19. Arpita says:

    very good but complicated

  20. Siv says:

    I have verry much impressed from Ur explanation………

  21. Nice tutorial and I’ve learned

  22. Nice article. Do you have any articles on PHP SESSIONS?

    Thanks.

  23. A.Master says:

    Please man im begenner at it all and am trying to put simple cookie at my site. I want to put input field and whin user click ok his name be cookie, this is the code

    — code begin —
    <?php
    if (isset($_COOKIE['MCookie']))
    echo "Welcome “. $_COOKIE[‘MCookei’]. “!”;
    else
    echo “Welcome Guest!*Please Enter Your Name”;
    ?>

    — code end —

    whin i try it i get “welcom !”
    no name in it the form is:

    — code begin —

    Enter Your Name

    Your Name:

    *Note:If you disabled cookies in your browser, Please enable it OR the site won’t work correctly

    — code end —

  24. A.Master says:

    Sry this is


    --- Code Begin ---
    Enter Your Name

    Your Name:

    *Note:If you disabled cookies in your browser, Please enable it OR the site won't work correctly
    --- Code End ---

  25. Clay says:

    A.Master… you mistyped the cookie name… in the line

    echo “Welcome “.$_COOKIE[‘MCookie’].”!”; you had put MCookei

  26. Memtech says:

    Hello Everyone,
    Great article !!!! thanks for sharing with us. Here I want share a simple one php cookies article for getting and setting value in cookie. for more details……… check out the following links………

    http://www.mindstick.com/Blog/231/PHP%20Cookies

    Thanks!!!!

  27. swellendam bnb…

    […]PHP Cookies Tutorial And PHP Cookies Examples « PHP Programming[…]…

  28. Copdir says:

    Copdir…

    […]PHP Cookies Tutorial And PHP Cookies Examples « PHP Programming[…]…

  29. Article Builder, Generate Unique Articles, membership for articlebuilder…

    […]PHP Cookies Tutorial And PHP Cookies Examples « PHP Programming[…]…

  30. semaj says:

    hey guys write cookies above the tag…..

  31. semaj says:

    hey guys write cookies above the html tag…..

  32. apple iphone 4 16gb, iphone 5, apple store, iphone 4s, iphone 3gs, iphone 4 weiß, i phone 5, iphone apps, ipod touch 4g, iphone 4 jailbreak…

    […]PHP Cookies Tutorial And PHP Cookies Examples « PHP Programming[…]…

  33. seduction reviews…

    […]PHP Cookies Tutorial And PHP Cookies Examples « PHP Programming[…]…

  34. karthik says:

    Hiiiiiii plz explain about cookies in a very simple way.i dont have any idea about php.now i am gng to know about php so plz provide information about cookies. why v r using cookies whta is the purpose.plz plz .send information to my mail (s.purushotham532@gmail.com)

  35. Akkuschrauber…

    […]PHP Cookies Tutorial And PHP Cookies Examples « PHP Programming[…]…

  36. roasted potatoes…

    […]PHP Cookies Tutorial And PHP Cookies Examples « PHP Programming[…]…

  37. Friendly says:

    Friendly…

    […]PHP Cookies Tutorial And PHP Cookies Examples « PHP Programming[…]…

  38. Your mind is basically a see-it-to-believe-it organ and when an abstract image, abstract background or abstract
    picture is introduced; it gives the brain practice to view things out
    of the ordinary. However, Free Premium are the best choice to opt for any sort of blog because they are extremely industrious and graceful themes.
    The PSP has made it so you can change the background,
    which empowers you to personalize your PSP to any
    skin you select.

  39. ankursharp says:

    Nice one. I have also just written cookie tutorial on http://www.techflirt.com/php/php-cookie. Anyone has feedback ?

Leave a reply to hariharan Cancel reply