PHP Cookies: How to Set Cookies & Get Cookies

By  on  

Cookies don't have to be an essential part of a website but can provide some of the "little things" that can set your website apart from the rest. Cookies are small tidbits of information that you save on the client's computer so that you can access them next time they visit the website. Session ID's are also usually held in cookies.

So what are the most popular uses of cookies? They are:

  • To store username/password information so that the user doesn't have to log in every time they visit the website ("remember me" sign ins).
  • To simply remember the user's name.
  • To keep track of a user's progress during a specified process.
  • To remember a user's theme.

Setting the Cookie

Setting a cookie requires a key, a value, and the amount of time to allow the cookie to exist.

$first_name = 'David';
setcookie('first_name',$first_name,time() + (86400 * 7)); // 86400 = 1 day

Above, we set the user's first name equal to 'David' (this data would actually come from a form or database but for the sake of the example we'll use my name). Then, we set a cookie with the key of "first_name" with the value 'David', and program it to expire 7 days from now.

Getting the Cookie Values

Now that we've set our cookie, it's time to get the value pretend they left your site and are coming back two days later).

echo 'Hello '.($_COOKIE['first_name']!='' ? $_COOKIE['first_name'] : 'Guest'); // Hello David!

Above, we check to see if the cookie with 'first_name' as the key still exists. If so, we use their name; if not, we call them "Guest". Basic cookies are that easy!

PHP cookies can be set with more specific directives, including path, domain, secure, and httponly.

setcookie('first_name',$first_name,time() + (86400* 7),'/~sugar/','davidwalsh.name',true,true);

This cookie is the same as above, but we're also telling the cookie to be applied towards the "~sugar" directory on the "davidwalsh.name" domain. It is for use only on an SSL connection and it may not be used by JavaScript.

Some other things to know about cookies:

  • Although you set an expiration on the cookie, a user can delete cookies at any time.
  • Cookies can only be accessed by the browser that set them (Firefox and IE don't share them)
  • A user can turn cookies off in their browser.
  • Never assume a cookie exists.

Recent Features

Incredible Demos

  • By
    JavaScript Canvas Image Conversion

    At last week's Mozilla WebDev Offsite, we all spent half of the last day hacking on our future Mozilla Marketplace app. One mobile app that recently got a lot of attention was Instagram, which sold to Facebook for the bat shit crazy price of one...

  • By
    Image Reflections with CSS

    Image reflection is a great way to subtly spice up an image.  The first method of creating these reflections was baking them right into the images themselves.  Within the past few years, we've introduced JavaScript strategies and CANVAS alternatives to achieve image reflections without...

Discussion

  1. I’m not 100% sure, but I think time()+(3600*7) = 7 hours.
    I think 3600 = 1 hour.

  2. @Shawn: You’re absolutely right. 3600 is an hour. I’ve updated the post. Thank you!

  3. EC

    What’s the difference between using setcookie() and header(“Set-Cookie….. ?

  4. @EC: Probably nothing — setcookie() is probably just a more elegant method of creating a cookie.

  5. aya

    hello, i just want to ask if it is possible to pass cookies to two different domain?

    thanks~

    • scott

      it is never ever possible to pass cookies between domains. like javascript’s inability to read you’r history but send you back to your last url or forward to your next url, cookies have limits that have long been set by web standards to keep users safe.

  6. hi, i have a problem with getting cookies in other page on other folder
    example
    i have set cookie on ../directory/query.php
    i will get cookie on ../directory/querylist.php

    but i dont get cookies on ../print/print.php

    why ?

    i used following code

    if (isset($_COOKIE['search']))
    {
        $search = $_COOKIE['search']; 
        $sql = $sql . stripcslashes($search);
        echo stripcslashes($search); 
    }
    

    what should i do for getting cookies in ../print/print.php

  7. benjamin

    how to install cookies please explain in a simple and clear way thanx.

  8. @Shawn: You’re absolutely right. 3600 is an hour. I’ve updated the post. Thank you!

    why don`t you use 606024nr. of days (secondsminuteshours)nr. of days

  9. Marvin Aya-ay
    echo 'Hello '.($_COOKIE['first_name']!='' -->?<-- $_COOKIE['first_name'] : 'Guest'); // Hello David!
    

    The question mark what does it mean?
    What here functionality their?
    Why it should put their?
    What's the purpose of that?
    plsss….ASAP

    • lowerdev

      It’s a short hand ‘if statement’.
      This line of code displays the username if the cookie exists. If not, it displays ‘guest’.

      simple example:

      $number = 5;
      echo 'the number is ' . ($number<10 ? 'smaller' : 'bigger') . ' than 10';
      // will say 'the number is smaller than 10'
      
      $number = 15;
      echo 'the number is ' . ($number<10 ? 'smaller' : 'bigger') . ' than 10';
      // will say 'the number is bigger than 10'
      
  10. Silver

    @Marvin Aya-ay: is this another way to write if-else construct and it correspond to:
    if($_COOKIE[‘first_name’]!=”){
    echo ‘Hello’.$_COOKIE[‘first_name’];
    }
    else{
    echo ‘Hello Guest’;
    }

  11. vivek

    i want to set cookie for a Minute how can set the time for just a second or minute

  12. jackie

    ok.. i have a problem..im very new at this, i’ve created a web pg were you can enter to another page with a user and password already determine in the code of the page.. it also hace a button wich gives ypu the option to create another user and password.. i .. tha problem is that when i want to enter the web page with another user and password(that i’ve already created) i cant.. how do i work this out..?

  13. Kaushik

    @anand acharya: Hi, you have to set the cookie as like:

    setcookie("cookiename","$_COOKIE['search']",time()+5184000,"/","your domain",true);
    

    the “/” will help u to get the cookie value in your entire domain. But remember one thing that u have to put the proper domain in the setcookie function like : http://www.example.com

  14. raj

    hello friend i tried setting and getting cookies,but even if i close my browser,i need to login again.But I dnt want it to work like that,i want it to redirect to my home page without asking me login details,any1 can help me

  15. Hey man, thanks so much for this post, I was working on a site where cookies had to be set dynamically in the middle of a page using an AJAX call to another directory, and I was scratching my brain for ages trying to figure out why I was unable to access the cookie from the current page, then just added ,’/’ to the end of setcookie(), and hey presto!

    Thanks a lot!

  16. Koti

    Hi,

    Created a cookie from http://www.example.com/test/createCookie.php

    SetCookie("MyCookie","Koti","/1001", (time()+3600*24));
    

    Domain: http://www.example.com
    Path: /1001

    And unable to read the cookie in the above path from http://www.example.com/test/readCookie.php.

    How to read the cookie from domain but in different path?

    Please help.

  17. Kevin

    Also…

    1) The format for expire-time is like a “Unix Timestamp”… use time() function.
    setcookie (“Name”, “value”, time() + 100, “/path/”, “.example.com”);

    2) Setting expire time to ‘0’ will expire (delete) the cookie at the end of the browser session (when browser is closed).
    setcookie (“Name”, “value”, 0, “/path/”, “.example.com”);

    3) To delete a cookie “immediately”, set the cookie value to anything (value=”deleted” or value=false is a good choice), and set the expire time to any date/time in the past.
    setcookie (“Name”, “deleted”, time()-5, “/path/”, “.example.com”);

    4) The strictly correct way to delete a cookie is to call setcookie with the name, path, expire, and all other parameters the same as the previous call to setcookie, and set the value=”” (empty).
    setcookie (“Name”, “value”, 0, “/path/”, “.example.com”); (set)
    setcookie (“Name”, “”, 0, “/path/”, “.example.com”); (delete)

    (see http://php.net/manual/en/function.setcookie.php)

  18. rumes

    ‘/>
    Your browser does not support iframes.

  19. Titochhabra

    Hello Everyone,
    This is a great article!!!!!!!! quite entertained
    Here you can check out, how to set and get cookies value in php in brief with example. Please click on the following links

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

    Thanks !!!

  20. explain about session and cookie in a simple way

  21. Thanks for giving us clear idea about cookie.

  22. pawan

    explain how to implement cookies in project

  23. Igor

    Can you please advise what may be wrong (FireFox 12, cookies enabled). Joomla part works fine producing the second line ‘Hi 66’, but in the first line the user id is not displayed.
    Thanks!

    $user =& JFactory::getUser();
    if (!$user->guest)
    {
    setcookie("UserID", $user->id, time() + 7 * 86400);
    echo 'Hello ' . $_COOKIE['UserID'];
    echo 'Hi ' . $user->id;
    }

  24. Another way to set cookie is:

    header(‘Set-Cookie: z=abc; expires=Sat, 19-Jul-2014 07:10:25 GMT; path=/; domain=.resnik.iz.rs’);

  25. Ioannis Cherouvim

    > To store username/password information so that the user doesn’t have to log in every time they visit the website

    Don’t you EVER do that. Please.

  26. Abdul Jabbar

    Good information. I just wanted to say that this statement is wrong that browsers like IE or Firefox do not share cookies because both of these and other browsers allow you to view individual cookie in their option settings. you can google so. There are folders set you can also go through them but sometimes they are persistently locked but still browsers themselves allow you to view any cookie information. Most of the websites have encoded or encrypted their information on cookie.

  27. please tell me how to retrive the cookie time duration

    • Kevin

      @Mr. Isaac

      If you mean that you have set a cookie on a users computer, and then at some later time, you want to read the expire time back to the server…

      You can’t. JavaScripe can’t access it either. You can only read the “value”.

      A workaround is to put a copy of the expire time somewhere in the “value” data (like at the beginning or end).

      So, for example:

      Then, later when you access the cookie data, you will see the value is something like:
      “My Cookie Data/1296096875”

      You can then use one of these PHP functions to “split” the cookie data from the time:
      preg_split() – Split string by a regular expression
      split() – Split string into array by regular expression /* deprecated in PHP 5.3.0 */
      spliti() – Split string into array by regular expression case insensitive /* deprecated in PHP 5.3.0 */
      str_split() – Convert a string to an array
      explode() – Split a string by string

      If you are only storing one cookie value, or if you’re setting multiple cookies with all the same expire time, you could set an additional cookie to hold the expire time:

      Then, access the value of $cookienameexpire to determine when all those cookies expire (no split required with this method).

    • Benji

      you can just read it and set it again to be the same value, it will just make the expire date further away

  28. Checkout my tutorial on how Cookies can withstand XSS or Direct cookie theft and impersonation on http://nativephp.com/archives/8 :) It will complement you post nicely.

    Thanks.

  29. Nevermore

    may I ask a question? Im newbie here in PHP, in my log in page, the cookie set. In my logout page, the cookie was unset. When Im clicking browser’s back button, it still go back to the previous page -_- . Why ?

    • Benji

      The cookie doesn’t remember the last page and some browsers don’t reload the page from the web server.

  30. Thanks for this post David, got my cookies working in no time.

  31. SAJJAD AHMED KHAN

    COOKIES SET ON CLIENT COMPUTER USE TO RETRIVE VALUES LATER

    setcookie("user",$_POST["textfield"],time()+30);
    

    BY USING THIS USE SET COOKIES
    NOW RETRIVE INFORMATION ON ANOTHER PAGE THEN

    if  (!isset($_COOKIE["user"]))
    	header("location: unreg.php");
    else
    	echo "Welcome  Mr. " . $_COOKIE["user"] . "Page2";
    
  32. sir,
    I have a problem with accessing cookies value in another page. My scenario is as follows: when we check remember me check box it sets username &passwd values on to the cookies & when we click to log in button it shows stored value of cookie other show welcome msg if we dont select remember me check box,
    Hope you will give me reply as early as possible.
    Thank you.

  33. Kevin

    Neeta Jadhav – I am not following your description of your problem. In particular, I don’t know what you mean “when we click to log in button it shows stored value of cookie”.

    First, you may already know this, but I have to mention it… It is not safe to store the plain-text of your users password and username in a cookie. Anyone who has access to the users computer (this includes any software, such as a virus) will be able to view the cookie file and see the users username and password, and then they could login as that user. Plus, if that user uses the same password on other sites (not recommended, but very common), then the users accounts on those other sites may also be compromised. It is much better to store a hashed form of the username and password.

    Second, it is not really recommended to store a username and password in a cookie, even hashed, because anyone who has access to the users computer can copy the cookie to a different computer, and they will be able to visit your site and and access your pages as if they were logged in as that user, even though they don’t have the actual username or password.

    A better choice is to use something like “PHP Sessions” which puts a “session-id” in a cookie rather than the actual username and password.

    If your site does not contain sensitive information, for example if you are just using a login to control what content your visitors are allowed to see on your site, then saving hashed usernames and passwords is probably secure enough. Keep in mind that with this, if someone gets the cookie file from one of your users that is logged in, they can share that cookie file with as many people as they want (could be hundreds or thousands of people), and they will ALL be able to visit your site and and access your pages as if they were logged in as that user.

    Anyway, back to your problem…

    Let’s say you have two pages on your site:
    example.com/content.php, and
    example.com/login.php

    First, suppose a user visits the page: …/content.php.
    Here, you check the values of the cookies. If they are logged in, you proceed to provide the user with the requested page. If they are NOT logged in, you redirect them to the …/login.php page.

    On the login page, you accept their username and password, and let them “check” (or “uncheck”) the remember-me checkbox. If they have provided the correct username/password, you hash the username and password, save them in a cookie, and let them proceed to the …/content.php page.

    If you use “regular” cookies, the user will remain logged in “forever” (until the cookies expire).

    The proper way to do this is:

    If the user selects to NOT remember-me (unchecks the remember-me checkbox), then use “session cookies”. These cookies will expire, and the cookies will be automatically deleted when the user closes all their browser windows. Then, the next time the user visits your site, they will have to login again.

    To implement a “remember-me” feature, you should decide on a how long you want to remember the users login.

    If the user checks the remember-me checkbox when they login, then you will set a “regular” cookie (not a session cookie) that expires in that amount of time. For example, you could remember the users login for 7 days. If the user logs-in today, and then comes back to your site within the 7-days, the login will be remembered and they will not have to login again. If they come beck to your site after the 7-days, they WILL have to login again at that time.

    The other thing you will have to do if the user checks the remember-me checkbox, is that whenever the user visits a page, you write the cookie again with a new “expiration time” set to 7-days (or as long as you want) from whenever they accessed that page.

    If you want to “remember” the users login “forever” there is a problem… regular cookies have to have an expire time. They can’t remain “forever”. In this case, you could set the cookies to expire many many years into the future. While this is not “forever”, for most cases it will be sufficient.

    Regardless of whether the user checks the “remember-me” checkbox or not, you could (if you want) provide a “logout” button on any of your pages. Clicking the button would delete the cookies then you could send the user to a “logged-out” page, or back to the “login” page.

    • FG

      Thanks for taking the time to explain this, Kevin.

  34. moh

    can you explain this code to me

    setCookie(‘xxxx’, 1, 5*60*1000);

    what is 1

    what is 1, 5*60*1000

    • nootanghimire

      @moh ,
      setcookie(‘xxxx’,1,5*60*1000);

      sets cookie with value 1 in key, “xxxx”, for 5*60*1000 seconds.

  35. WS

    DIRE WARNING:

    Do not ever use cookies to remember a password. Use a cryptographic token that is associated with a session on your server. A cookie is easily compromised (e.g. someone using the computer can just look at it, cookies are transmitted in plain-text over the wire, and are vulnerable to XSS attacks, and tons of other attack vectors). Users often use the same password for many sites so one tiny leak opens a dam.

    I understand that many people reading this page are new to web development and this seems like an unnecessary complication, but this is a very bad practice. Investigate how to maintain a session and issue a token.

  36. What would the domain name be set as for this cookie?

    $first_name = 'David';
    setcookie('first_name',$first_name,time() + (86400 * 7));
    
  37. Divya

    I am not understanding why do we use $_COOKIE and how to use them?

  38. I had this site on for years now. Somehow I must have deleted the key session cookie and can no longer open this site . I tried to reinstall it and it keep saying there is “no key session cookie”. I have no idea what this means as I really don’t know much about computers. Can you help? I am up there age wise and really don’t have a clue. Just want my poker site back.
    Thanks for any help you can give……rock

  39. Bradly

    Hello Sir, i got an interesting thread, i would like to ask if there is a possible solution of removing unknown cookies, let say for example i have set a cookie ..setcookie(“user”,”value”);
    all other cookie will be remove, an attacker creates a cookies, and i want to prevent them.
    how could i get the cookie[‘name’] if it is equal to the cookie that i’ve set, and if not equal then remove it or unset that user defined cookies.

    i wan’t to get the name value of undefined cookie.
    and unset it.

  40. logan

    Hey, I want to set up a cookie in my wordpress account so that each time when user selects particular product of my company, I get to know the most visited item of my company using only ‘cookies’. PS – I do not want to use any plugin or widget for this purpose. It’d be better if I build it on my own using cookies in PhP. Thank You. :)

  41. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. I.e. a cookie is often used to identify a user. A cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. Cookies are part of the HTTP header, so cookies must be called before any output is sent to the browser. This is the same limitation that HTTP header has.
    To read more in details please visit—–

    http://www.mindstick.com/blog/231/PHP%20Cookies
    http://www.w3schools.com/php/php_cookies.asp

  42. Evelyn
    $s_register=session_id();
    
    session_start();
    
    if(empty($s_register)){
         
     $s_register = session_id();
     
     $c_register = $_COOKIE["PHPSESSID"];
     
     $_SESSION['time']  = time();
    
     $last_activity = date('Y-m-d g:i:s', $_SESSION['time']);
    
     setcookie('last_activity',$last_activity,time() + (86400 * 7)); // 86400 = 1 day
    }
    

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!