PHP Cookies: How to Set Cookies & Get Cookies
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 dayAbove, 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.
Comments
Be Heard!
Share your thoughts without being a jerk! And wrap your code in <code> tags, f00!
I’m not 100% sure, but I think time()+(3600*7) = 7 hours.
I think 3600 = 1 hour.
@Shawn: You’re absolutely right. 3600 is an hour. I’ve updated the post. Thank you!
What’s the difference between using setcookie() and header(“Set-Cookie….. ?
@EC: Probably nothing — setcookie() is probably just a more elegant method of creating a cookie.
hello, i just want to ask if it is possible to pass cookies to two different domain?
thanks~
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.
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
how to install cookies please explain in a simple and clear way thanx.
why don`t you use 606024nr. of days (secondsminuteshours)nr. of days
echo ‘Hello ‘.($_COOKIE['first_name']!=” –>?<– $_COOKIE['first_name'] : 'Guest'); // Hello David!
The question mark what does it mean?
What here funtionality their?
Why it should put their?
What's the purpose of that?
plsss….ASAP
@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’;
}
i want to set cookie for a Minute how can set the time for just a second or minute
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..?
@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
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
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!
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.
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)
‘/>
Your browser does not support iframes.
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 !!!
explain about session and cookie in a simple way
Thanks for giving us clear idea about cookie.