PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<headers_sentHyperwave>
view the version of this page
Last updated: Sat, 05 Jul 2003

setcookie

(PHP 3, PHP 4 )

setcookie -- Send a cookie

Description

bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]])

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace. If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.

Note: In PHP 4, you can use output buffering to send output prior to the call of this function, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files.

All the arguments except the name argument are optional. You may also replace an argument with an empty string ("") in order to skip that argument. Because the expire and secure arguments are integers, they cannot be skipped with an empty string, use a zero (0) instead. The following table explains each parameter of the setcookie() function, be sure to read the Netscape cookie specification for specifics on how each setcookie() parameter works and RFC 2965 for additional information on how HTTP cookies work.

Table 1. setcookie() parameters explained

ParameterDescriptionExamples
name The name of the cookie. 'cookiename' is called as $_COOKIE['cookiename']
value The value of the cookie. This value is stored on the clients computer; do not store sensitive information. Assuming the name is 'cookiename', this value is retrieved through $_COOKIE['cookiename']
expire The time the cookie expires. This is a unix timestamp so is in number of seconds since the epoch. In otherwords, you'll most likely set this with the time() function plus the number of seconds before you want it to expire. Or you might use mktime(). time()+60*60*24*30 will set the cookie to expire in 30 days. If not set, the cookie will expire at the end of the session (when the browser closes).
path The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.
domain The domain that the cookie is available. To make the cookie available on all subdomains of example.com then you'd set it to '.example.com'. The . is not required but makes it compatible with more browsers. Setting it to www.example.com will make the cookie only available in the www subdomain. Refer to tail matching in the spec for details.
secure Indicates that the cookie should only be transmitted over a secure HTTPS connection. When set to 1, the cookie will only be set if a secure connection exists. The default is 0. 0 or 1

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, autoglobals such as $_COOKIE became available in PHP 4.1.0. $HTTP_COOKIE_VARS has existed since PHP 3. Cookie values also exist in $_REQUEST.

Note: If the PHP directive register_globals is set to on then cookie values will also be made into variables. In our examples below, $TextCookie will exist. It's recommended to use $_COOKIE.

Common Pitfalls:

  • Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.

  • Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string (""), and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client.

  • Cookies names can be set as array names and will be available to your PHP scripts as arrays but seperate cookies are stored on the users system. Consider explode() or serialize() to set one cookie with multiple names and values.

In PHP 3, multiple calls to setcookie() in the same script will be performed in reverse order. If you are trying to delete one cookie before inserting another you should put the insert before the delete. In PHP 4, multiple calls to setcookie() are performed in the order called.

Some examples follow how to send cookies:

Example 1. setcookie() send examples

<?php
$value = 'something from somewhere';

setcookie ("TestCookie", $value);
setcookie ("TestCookie", $value,time()+3600);  /* expire in 1 hour */
setcookie ("TestCookie", $value,time()+3600, "/~rasmus/", ".example.com", 1);
?>

Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name. To see the contents of our test cookie in a script, simply use one of the following examples:

<?php
// Print an individual cookie
echo $_COOKIE["TestCookie"];
echo $HTTP_COOKIE_VARS["TestCookie"];

// Another way to debug/test is to view all cookies
print_r($_COOKIE);
?>

When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser. Examples follow how to delete cookies sent in previous example:

Example 2. setcookie() delete examples

<?php
// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", ".example.com", 1);
?>

You may also set array cookies by using array notation in the cookie name. This has the effect of setting as many cookies as you have array elements, but when the cookie is received by your script, the values are all placed in an array with the cookie's name:

Example 3. setcookie() and arrays

<?php
// set the cookies
setcookie ("cookie[three]", "cookiethree");
setcookie ("cookie[two]", "cookietwo");
setcookie ("cookie[one]", "cookieone");

// after the page reloads, print them out
if (isset($_COOKIE['cookie'])) {
    foreach ($_COOKIE['cookie'] as $name => $value) {
        echo "$name : $value <br />\n";
    }
}

/* which prints

three : cookiethree
two : cookietwo
one : cookieone

*/
?>

For more information on cookies, see Netscape's cookie specification at http://www.netscape.com/newsref/std/cookie_spec.html and RFC 2965.

You may notice the expire parameter takes on a unix timestamp, as opposed to the date format Wdy, DD-Mon-YYYY HH:MM:SS GMT, this is because PHP does this conversion internally.

Microsoft Internet Explorer 4 with Service Pack 1 applied does not correctly deal with cookies that have their path parameter set.

Netscape Communicator 4.05 and Microsoft Internet Explorer 3.x appear to handle cookies incorrectly when the path and time are not set.

See also header() and the cookies section.



User Contributed Notes
setcookie
add a note add a note
thomas at proton dot mine dot nu
29-Jun-2003 06:07

Browsers like Opera and Mozilla are told to need the full page loaded to accept cookies (that's what bmatzelle at NOSPAM dot yahoo dot com said).
You can use cookies at reloading pages, however after sending out all headers call exit(); to stop the rest of the script, so the actual page content is not sent out.

winfield at support dot email dot ne dot jp
20-Jun-2003 04:41

This is a revised edition of a way determining if user's browser can handle cookie.
Call this function at the begining of your global routine.

function cooktest() {
// Most of all, if certain variable your script USUALLY get is NOT given ('mode' for exapmple)
if(!isset($_GET['mode'])) {
setcookie("check_cookie", "on", time()+3600);
// If 'cooktest' (a var ONLY for this function) is not given (means First Time)
   if (!isset($_GET['cooktest'])) {
    Header("Location: $_SERVER[PHP_SELF]?cooktest=1");
    exit;
   }
// If sctipt can NOT read COOKIE after reloaded
  elseif (!isset($_COOKIE['check_cookie'])) {
     print <<<EOM
<html>
<body>
Sorry. You should set COOKIE enabled.
</body>
</html>
EOM;
    exit;
   }
}}

Thank you ,Kayvan.
Best Regards,
Tats

fandelem at Hotmail dot com
17-Jun-2003 11:27

i have noticed this after 5 pain-staking hours:

Going to indiewatch.com/test.php?do=gen, which does:

setcookie('id', $unique_id, $expiry);

then, closing browser, re-opening, and going to www.indiewatch.com, will yield a blank $_COOKIE array.

However, going to www.indiewatch.com/test.php?do=gen, having the cookie being set, then closing the browser, re-opening, and going to www.indiewatch.com will yield an element in $_COOKIE called 'id'.

Are there any solutions for this?  Perhaps a better one than I will contribute, so I wait in anticipation for responses..  below is my solution:

setcookie('id', $unique_id, $expiry,'',str_replace('www.','',strtolower($HTTP_HOST)));

this will allow someone who has created a cookie by going to www.indiewatch.com to have it loaded when they go to indiewatch.com.

cheers,

k.

Cerium at x2productions dot net
27-Apr-2003 02:38

an interesting note, under windows xp, my scripts were only able to store 20 cookies for any one domain/folder combo.

Not that you should need that many, but just incase...

23-Apr-2003 11:37
> Bear in mind if you tried to store MULTIPLE STRING VALUE IN ONE COOKIE,
> you have to employ addslashes prior to serializing them(sound odd but
> I just dunno why, myself has been spending tons of time to figure it out).

This code (from above):
<?
$array[0]=addslashes("a");//it doesn't work if you remove the addslashes()
$array[1]=addslashes("b");
$array[2]=addslashes("c");

echo serialize($array);
?>

Returns:
a:3:{i:0;s:1:"a";i:1;s:1:"b";i:2;s:1:"c";}

... and so does the same code without addslashes():
<?
$array[0]="a";
$array[1]="b";
$array[2]="c";

echo serialize($array);
?>

Returns:
a:3:{i:0;s:1:"a";i:1;s:1:"b";i:2;s:1:"c";}

Possibly you need addslashes() if your values contain ' or " but I never needed it (if "magic quotes" is on). In such a case you could just use addslashes() on the serialized string.

janhouse00 at hotpop dot com
22-Apr-2003 09:43

Bear in mind if you tried to store MULTIPLE STRING VALUE IN ONE COOKIE, you have to employ addslashes prior to serializing them(sound odd but I just dunno why, myself has been spending tons of time to figure it out).See the following scripts:

//makecookie.php

<?
$array[0]=addslashes("a");//it doesn't work if you remove the addslashes()
$array[1]=addslashes("b");
$array[2]=addslashes("c");

//print_r($array)

$s=serialize($array);
setcookie("cookies",$s,time()+86400);
?>

//test.php
<?
if(isset($cookies)){
$array=unserialize(stripslashes($cookies));
foreach($array as $i=>$cookie){
print"
$i => $cookie";
}
}
?>

serrano at no dot emails dot pls
19-Apr-2003 04:41

Hi,
it seems most of the coders get stuck with expiring the cookie, and using the cookie in the same document as they set it.
first case, you will face many problems when using expiring cookies for session data etc.
SO, SOLUTION: don't use expire at all, or use it to expire the cookie once browser session is closed (0). then, keep track of cookie expires in database, and refresh this each time the user gets this cookie renewed. I always re-set expiration when user is logged in and accesses any admin pages. no time difference matters will occur this way.
SOLUTION #2: make your clients life easier, and make a little front-end like like this: have variables (an array, for e.g) for your cookied user data (for me, usually only username and an authentication cookie). Then, at code startup, make sure client does not spoof these variables (might be necessary, but not alway). two things left to do are: check if user sent cookie data, and if did, update your variables, and, when you set a cookie, set your variables also. a real-life example:

$user = array (
  "name" => "",
  "pass" => "",
  "session" => "",
  "id" => ""
  );
if ($_COOKIE[name]) $user[name]=$_COOKIE[name]);
if ($_COOKIE[session]) $user[session]=$_COOKIE[session]);

if ($user[name] && $user[session]) {
  # here check your database if username and session are valid. if not, drop user out here to the login screen (eg. include ("login.html"); die();)
  # if they are, renew cookies
  setcookie ("name", $user[name] (...) );
  setcookie ("session", $user[session] (...) );
  # update expiration in your database here
  }
elseif ($user[name] && $user[pass]) {
  # user submitted credentials, check database if those are valid, if not, drop user back to login screen (see above).
  $result = mysql_query ("select id from users where username='$user[name]' and pass=password('$user[pass]')");
  if (!mysql_num_rows ($result)) {
     include ("login.html");
     die();
    };
  # otherwise, fetch user id, generate a cookie, send him, and update db
  $row = mysql_fetch_array ($result);
  $user[id] = $row[id];
  $user [session] = md5(uniqid(mt_rand()));
  setcookie ("username", $user[name]);
  setcookie ("session", $user[session]);
  #update database, like this:
  mysql_query ("update users set session=$user[session], expire=".(time()+3600)." where user_id = $user[id]");
  }
else {
  # if has no cookies, not submitted credentials, drop login page
  include ("login.html");
  die ();
  };

from this on, you can use the $user array for anything. you can use more cookies as well, and you can skip most of the code if you do not want authentication (but then, why expire and security at all ? :) I hope this code works fine, wrote from scratch... but, you can intagrate any startup procedure related to client sessions etc.
as you can see, there is no need at all of any redirects (Location: etc.), which is a completely innecessary thing.
a little explanation on the database: I assumed you have a table like this:
create table users (id int(32) primary key not null auto_increment, username char(16), pass char(16), session char(32), expire int(64));
and remember to store passwords using mysql's password ()function, so passwords will be safe. this table will be fast for many users as well, and should you change any database user data later in this script, you can reference it with $user[id]... in this case _REALLY_ make sure client will not spoof this variable of yours! :)

soreman at abv dot bg
11-Apr-2003 05:26

If you experience problems on Microsoft Information Server (IIS) when setting a cookie via PHP and when PHP is running as a CGI binary it is not setting the cookie. After spending many hours on what the problem is here is what happens:

When you invoke setcookie and redirect to another page you will not have your cookie set, because it seems that IIS doesn't set the cookie unless you actually send some contents to the browser. Therefore if you want to set a cookie and then redirect to another page you will have to do the redirection via JavaScript and/or HTML if you want your script to work on IIS.

lexcomputer
19-Mar-2003 04:28

** Modifying from the former poster **

The script that help to solve the problem of calling cookie for the first time, which return nothing (strlen($cookie)=0).

<?php
// This script named testcookie.php
$cc = strlen($mycookie);
if($cc==0){
setcookie("mycookie", "mycookie", time()+3600);
//3600 is an hour, in seconds
Header("Location: testcookie.php");
// testcookie.php is the document itself
exit();
} else {
if (!isset($mycookie)) {
echo "Your browser does not support cookie";
} else {
echo "Your browser does support cookie";
}
}
?>

hope this script could  help you :-)

till'at'klimpong'dot'com
17-Mar-2003 08:43

As an addition to my earlier post (in rage):

The reason why is that I was not able to use the variable that had an underscore in its name within PHP. I tried to echo it, I tried using it in if-statements etc., even a print_r($_COOKIE) returned emptry.

Go figure.

ppegah at yahoo dot com
13-Mar-2003 10:25

Here is a very simple way to finde out if the browser supports cookie:

setcookie("check_cookie", "on", time()+(60));
$refreshed= "set";
if (!isset($refreshed)) {
//forcing the browser to reload
echo "<META HTTP-EQUIV=Refresh CONTENT=\"0\">\n";
}
if (!isset($check_cookie)) {
//Browser does not accepting cookies
//Do something
} else {
//The browser accepts cookies
//Do something else
}

I hope it helps somebody :-)
Reagrds
Kayvan

oz at austdesign dot co dot uk
07-Mar-2003 08:25

I have had a similair problem with a login script using cookies on Safari on MacOS X and IE6 on Windows XP

The original script looked like this:

----Code-----

#Encrypt Password
$password = md5($password);


if(authLogIn($username, $password)){
  setcookie ('user', $username,time()+3600);
   setcookie ('password', $password,time()+3600);


header ("Location: adminhome.php");
exit;
}else{
header ("Location: index.php");
exit;
}

------------------

I changed the setcookie calls to be a complete cookie and only the password was written.

I then figured out that the two browsers do not except cookies that are written directly from the form that submitted it.

The password was encrypted so the value was different to what was on the form.

the following code is the final working version with a work around to get the username to be written to a cookie:

-----code-----

#Encrypt Password
$password = md5($password);
$user = $username;

if(authLogIn($username, $password)){
   setcookie ('user', $user,time()+3600, '/','www.siteaddress.co.uk');
   setcookie ('password', $password,time()+3600, '/','www.siteaddress.co.uk');

header ("Location: adminhome.php");
exit;
}else{
header ("Location: index.php");
exit;
}

----------------

metalblend
06-Mar-2003 05:03

I had trouble figuring out why I couldnt set a cookie and use header("Location: $PHP_SELF") in IE6 .. caching seemed to be killing cookies, until I tried header("Cache-Control: private")

setcookie("cookie","value",time()+3600);
header("Cache-Control: private");
header("Location: ".$PHP_SELF);

Hope that helps someone, and if someone would like to explain why this happens that'd be nice.

kb at hostedstuff dot com
25-Feb-2003 12:06

I had problems deleting cookies on msie 6.0.2800.

This did not work:
setcookie ("TestCookie", "", time() - 3600);

This worked fine:
setcookie ("TestCookie", " ", time() - 3600);

Strange, but true :-)

bikeman82 at hotmail dot com
24-Feb-2003 07:23

I found out that having a "Location: "-header sent (through header()) and setting a cookie with setcookie() is something that doesn't work on an IIS-server (for as far as I know up to version 5.0) and PHP installed as a CGI.

Have a look at this Microsoft-page: http://support.microsoft.com/default.aspx?scid=KB;en-us;q176113

Easiest way to solve this is installing PHP as an ISAPI, but I guess the proposed solution works as well (need to go through some testing before I'm sure about that).

Greetz,
Bikeman

mikezivin at yahoo dot com
09-Feb-2003 09:19

When developing web applications on your local machine and using "localhost" as your domain, cookies will not be set correctly using IE6 (maybe other IEs as well) if you specify "localhost" as your domain when using setCookie(). If you read the Netscape spec, there is a note:

"Only hosts within the specified domain can set a cookie for a domain and domains must have at least two (2) or three (3) periods in them to prevent domains of the form: ".com", ".edu", and "va.us". Any domain that fails within one of the seven special top level domains listed below only require two periods. Any other domain requires at least three."

Lebbeous Weekley
06-Feb-2003 12:30

I'm not completely sure how appropriate it is to post Javascript in this forum :) , but since the problem of differing client/server time when setting cookies keeps coming up ...

In situations where I have users log in or do anything with a form that leads to the generating of the cookie on the next page, I have this Javascript function in the login page:

 //
 // getTimestamp()
 //   This function sets the value of a hidden
 //   variable in the login form to the current
//   time, expressed in seconds since the
 //   epoch, according to the client's computer.
 //
 function getTimestamp(form)
 {
  var t = new Date();
   var timestamp;

   // Date.getTime() returns milliseconds,
   // so divide by 1000 for seconds
  timestamp = Math.floor(t.getTime() / 1000);
   
   form.time.value = timestamp;

   return true;
 }

This of course requires a) a hidden variable called 'time' to be placed in the form, and b) an onSubmit="return getTimestamp(this);" element in the form tag. Then the PHP script can take $_POST['time'] and use it instead of time() in calculating your cookie's expiration date.

And of course it also wouldn't work when you want to send a cookie that doesn't come after a form submission, but still maybe some will find it useful.  If some browsers meddle with the time already to try to correct client/server discrepancies, a browser check could be added to the Javascript or to the PHP.

geoffrey at nevra dot net
05-Feb-2003 08:04

when trying to set a cookie with path, don't forget the starting / to the path

the following code won't work and will set a cookie for the domain 'example.compath' (tested with php 4.2.3 and IE 5.5)

setcookie('foo', 'bar', time()+3600, 'path', 'example.com');

the following code will work:

setcookie('foo', 'bar', time()+3600, '/path', 'example.com');

hope it helps

Anonymous
04-Feb-2003 12:03

<?php
if(ereg("[0-9].[0-9].[0-9].[0-9]",$HTTP_HOST)){
$domain = $HTTP_HOST;
} else {
$domain = eregi_replace("www.","",$HTTP_HOST);
$domain = ".".$domain;
}
if(isset($uidcookie)) {
$set = "Your Unique ID is: $uidcookie";
} else {
srand ((double) microtime() * 1000000);
$uniq_id = uniqid(rand());
setcookie ("uidcookie", $uniq_id, time()+86400, "/", "$domain");
$set = "Your Unique ID is now: $uniq_id";
$log = "log.txt";
$fp= fopen($log,"a");
$uniqid = "| Unique ID: $uniq_id | ";
$datelang = "Date Created: ";
$date = date("l - F j, Y - g:i a");
$ip = " | IP Address: $REMOTE_ADDR | ";
$referer = " | $HTTP_REFERER ";
$incomingpage = " | $PHP_SELF ";
fputs($fp,"$uniqid$datelang$date$incomingpage$referer$ip\n");
fclose ($fp);
}
?>

peterg at NOSPAM dot mildewhall dot com
30-Jan-2003 01:20

I cookified my Nokia 6310i !

This must come before any WAP headers:

<?php
if ( $_COOKIE["LV"] )
   {
  setcookie ("LV", "", time() - 3600); // destroy old cookie
   setcookie ("LV", date ("l dS of F Y h:i:s A"),time()+3600); // "update" by adding a new one
  }
else
   {
   setcookie ("LV", date ("l dS of F Y h:i:s A"),time()+3600); // add a new cookie
   }

... and then when you actually want to read it, stick this somewhere in your card deck:

<?php if ($_COOKIE["LV"]) echo "Last visit " . $_COOKIE["LV"] . "<br/>"; ?>

neil
20-Jan-2003 04:34

Some versions of IE6, when you drop a non-persistent cookie, handle this incorrectly and instead drop a persistent cookie.

This is not PHP's fault: ) Rather it is a bug in these versions of IE6. I am posting this because people may be programming session IDs and tokens in what they believe to be non-persistent cookies. Specifically, IE6 build 6.0.2800.1106CO (SP1) does this.

IE6, in this case, will make your application insecure. You should notify IE6 users to manually delete their cookies after their session is completed. Will they do this, no. At least you did your part to notify them of the risk.

We found this to be true after an ethical hack which condemned the use of SessionID's in query string, even if the entire session begins, happens, and ends, in https. M$ Proxy Server (here we go with M$ crappy security) writes these session ID's to it's proxy logs. Since Proxy Server is easily comprimised with numerous well known hacks, your sessions can be. I have seen the logs and seen the sessionid's in https.

Unfortunately, these EH fellows are forgetting that most user's systems are less secure and less patched than most ISP's and corporate proxy servers. We are simply moving the vulnerability to the client by using cookies. If it were up to me, I would leave sessionid in query string.

I was proven right in the case with this browser.

thx
Neil

sjohnson -AT- fuzzygroup.com
11-Jan-2003 12:35

It sounds like you need to set the expiration date for the cookie.  Try this:

setcookie("tekka_p","HOWDY_DOO",time() + 86400);

This would set the cookie's expiration date to one day from the time it is set.

If you have the time period for the cookie declared in a variable make sure that it is valid for the current scope. I had time()+$cookie_period but $cookie_period was Null in that scope so my cookies were set and then immediately vanished.

Those cookies did not taste good at all.  Kinda Cement + Chocolate Chip.  Icky.

bmatzelle at NOSPAM dot yahoo dot com
10-Jan-2003 03:03

I was having problems with making cookies work consistently in my web browser.  I was running setcookie() then immediately redirecting the user to a different page like so:

setcookie("name", "value");
header("Location: some_page.php");

For some reason the cookie would set itself with IE but inconsistently (about 10% of the time) with Mozilla and Opera. These two browser do not accept cookies unless the full page is loaded. The workaround is to only set cookies on pages that are never re-directed. It is unfortunate but required.

mleer at sp dot nl
19-Dec-2002 06:50

P3P is a good idea. But.
IE 6 features an inadequate definition of third party cookies.
If your site is hosted on server A and your PHP stuff is coming in a framesetting from server B your setcookie-attempts will be blocked when default privacy settings are deployed. Your secondparty-cookie will be regarded as a thirdparty-cookie.

So what you do is not read the P3P-Internet Explorer 6-manual at MS but send a header like

header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');

before doing the setcookie-thing. This will enable your cookie to survive any IE-6 privacy settings.

You won't do this if you're working for some doubleclick institution, because if you do, you... you...well... you are not a very nice person!

Jester at freee2code dot net
28-Nov-2002 01:05

For some more information on setting and retrieving cookies with PHP see: http://www.free2code.net/tutorials/php/cookie2

If anyone is having trouble with cookies this tutorial should help you get it working. Explains each parameter and what they do.

troy at digigator dot com
31-Oct-2002 03:16

The comments above about being able to set or read cookies for co.uk are incorrect.

Only hosts within the specified domain can set a cookie for a domain and domains must have at least two (2) or three (3) periods in them to prevent domains of the form: ".com", ".edu", and "va.us". Any domain that fails within one of the seven special top level domains listed below only require two periods. Any other domain requires at least three. The seven special top level domains are: "COM", "EDU", "NET", "ORG", "GOV", "MIL", and "INT".

sijis at ruizbelvis dot org
20-Oct-2002 06:09

If you try to set an array of cookies by using array notation make sure you have the same expire length of the cookie. If you don't, only the first cookie in the array or cookies matching the same expiration date will be created.

// This will NOT work.
setcookie("value[one]","value1",time()+5184000);
setcookie("value[two]","value2",time()+14400);

// This will work.
setcookie("value[one]","value1",time()+5184000);
setcookie("value[two]","value2",time()+5184000);

It also does NOT matter when the expiration date is for the cookie. They can be set for different dates.

kage-chan at users dot sf dot net
04-Aug-2002 03:30

If you ever have problems deleting a cookie, no matter with which browser, try it like below:

setcookie ('CookieName', '', (time () - 2592000), '/', '', 0);
(Note: all quotation marks are _single_ quotes)
This is the only method that worked for me to delete a cookie. I hope it works fo you too :)

public at macfreek dot nl
13-May-2002 10:48

Regarding the time difference between client and server, (aksed by aortiz@onlinetraffic.com):

Yes, this a a problem. However, it's not the fault of PHP, this problem is inherent to the specification of Cookies by Netscape. Thankfully a newer specification by the IETF (the organisation that made all Internet protocols like HTTP, SMTP, TCP, IP, SMTP and POP3) fixes this by using the time *difference* instead of the absolute time. (it uses the Max-Age attribute instead of the expires attribute)

The disadvantage is that probably not all browsers support it (I haven't checked to be honest). This new specification is over 5 years old (feb 1997), but in particular IE has the habit of ignoring standards :-(

public at macfreek dot nl
13-May-2002 10:31

Your link to the Cookie specification is very out-of-date. There are two newer specification which are adopted by the IETF:

http://www.netscape.com/newsref/std/cookie_spec.html "Persistent Client State -- HTTP Cookies"
http://www.ietf.org/rfc/rfc2109.txt "HTTP State Management Mechanism"
http://www.ietf.org/rfc/rfc2965.txt "HTTP State Management Mechanism"

RFC 2965 specifies the Set-Cookie2 syntax, RFC 2109 specifies the Set-Cookie syntax, which is commonly used (and I recommend is used at the moment).

These RFC have a better security section, and deal with things like Spoofing (see exerpt bellow):

Proper application design can avoid spoofing attacks from related domains.  Consider:

1. User agent makes request to victim.cracker.edu, gets back
  cookie session_id="1234" and sets the default domain
  victim.cracker.edu.

2. User agent makes request to spoof.cracker.edu, gets back cookie
  session-id="1111", with Domain=".cracker.edu".

3. User agent makes request to victim.cracker.edu again, and
  passes

  Cookie: $Version="1"; session_id="1234",
          $Version="1"; session_id="1111"; $Domain=".cracker.edu"

  The server at victim.cracker.edu should detect that the second
  cookie was not one it originated by noticing that the Domain
  attribute is not for itself and ignore it.

regina at hitel dot net
01-May-2002 07:24

[Editor's Note: The initial post of the code has been erased (since it was buggy). However, here is the acknowledgement just to maintain credit :)

/************************************************************

FUNCTION SEND_HTCOOKIE

Author: Van Carney (van@Webfreshener.com)
©2000-2002 Webfreshener.com

last rev: 4/21/02 3:56:47 AM

HTTP Cookie generation routine
takes variable number of args and writes cookie to header
per the Netscape Cookies Spec

This user function is written to mimic the built-in setcookie()
function in PHP.
This was done as problems were noticed with that function
when writing cached cookies from within Object Scopes.
PHP would not write a cached cookie when setcookie()
was called inside an object. This function has been tested
and workes quite nicely in multiple scopes.

usage:
send_htCookie(string varname (required),string varval,string expire,
string path, string domain, bool secure);

*************************************************************/
]

Thanks to Van Carney.
But, that function has a little problem in PHP 4.2.0.
So, I did re-write it, below.

/******************************
ysage:
send_htCookie(string varname (required),string varval,int expire,
string path, string domain, bool secure);
******************************/
function send_htCookie() {
 $vars=array('varname','varval','expire', 'path','domain','secure');

 for ($i=0;$i<func_num_args();$i++) {
    ${$vars[$i]}=func_get_arg($i);
 }

 if (!$varname) { return false; }

 $COOKIE = "Set-Cookie: $varname=$varval";
 if (isset($expire) && ($expire > 0)) {
    $COOKIE .= "; EXPIRES=".
    gmdate("D, d M Y H:i:s",$expire) .
    " GMT";}
 if (isset($domain)) { $COOKIE .= "; DOMAIN=$domain"; }
 if (isset($path))   { $COOKIE .= "; PATH=$path"; }
 if (isset($secure) && $secure>0) { $COOKIE .= "; SECURE"; }

 header($COOKIE,false);
return true;
}

greg-php at elysium dot ltd dot uk
18-Dec-2001 04:11

As already stated above, one reason for the failure of expiration-based cookies can be an incorrect local time on the CLIENT. Two more points about this:

1. Not all browsers suffer from the problem. Netscape doesn't, and it appears to do the sensible thing: it compares the cookie expiry time with the server's notion of the current time, and then adds the difference onto its own notion of the time for storage.

2. Local time includes TIMEZONE. A cookie expiring at 2 p.m. GMT has already expired at 11 a.m. on the same day if the timezone is (correctly or incorrectly) set to EST. Beware users whose computers were preinstalled in another country and who have only corrected the visible clock time!

robert at ourwebhome dot com
05-Dec-2001 07:41

Internet Exploer 6 now requires sites that set cookies to have P3P policies.

From the Microsoft page:
"Internet Explorer 6 implements advanced cookie filtering that is based on the Platform for Privacy Preferences (P3P) specification. By default, Internet Explorer 6 blocks third-party cookies that do not have a compact policy (a condensed computer-readable privacy statement) or third-party cookies that have a compact policy which specifies that personally identifiable information is used without your implicit consent. First-party cookies that have a compact policy which specifies that personally identifiable information is used without implicit consent are downgraded (deleted when you close Internet Explorer). First-party cookies that do not have a compact policy are leashed (restricted so that they can only be read in the first-party context)."

See:
http://support.microsoft.com/default.aspx?scid=kb;EN-US;q260971&GSSNB=1

For more about P3P:
http://www.w3.org/P3P/

paul at liversidge dot net
29-Oct-2001 11:59

It's also worth pointing out that all inbound variable names and cookie names with periods in them will be converted to underscores with PHP. Ultimate Bulletin Board uses such a name for its cookies, the name is 'ubber1234567.8901', where the number is unique to your board. Use the following PHP code to read this value...

echo ($ubber1234567_8901);

It took me ages to work this one out!!!

agx at REMOVE dot icicampus dot it
30-Aug-2001 01:38

Set a cookie and redirect using:

$url = $_SERVER['REQUEST_URI'];
if ( strpos( $url, '?') == false ) {
$url .= '?setcookie=1';
} else {
 $url .= '&setcookie=1';
}
Header('Location: '. $url);

If your cookie is empty and setcookie==1 then the browser does not supports cookies (i have plenty of robots visiting my site and do not wanna a create a new session on each page they visit :-P )

emmajane at xtrinsic.com
23-Aug-2001 02:34

After much frustration (is there any other way to do these things?) I found the following browsers need a 'full' cookie instead of the simple setcookie(one, two). I used the link to netscape at the top to figure how what all the parameters were that I needed to set. (PHP 3.x, don't know if it would make a difference if I'd be using PHP 4.x, but I doubt it would...)

BROWSERS THAT NEED A FULL COOKIE
PC: IE 5, Opera 5
Mac: NS 6.x

BROWSERS THAT DIDN'T NEED A FULL COOKIE
PC: NS 4.x
Mac: IE 5

I checked for a browser reference chart that had a list of all these, but didn't find one. If anyone knows of a full chart, maybe they could post the URL here?

raynet at edu dot lahti dot fi
07-Aug-2001 09:24

The well know "two-dots" issue with cookie domains might be solvable by using the correct domain name, eg:

slashdot.org.

instead of

slashdot.org

the last dot is actually the root domain.

Also I've noticed no problems with cookies when I'm using the form:
setcookie("variablename","$variable");

In my opinion there is no need for the expiration field, or any other fields. Just do the stuff on the server. Example:
$session_id = md5(uniqid(rand()));
<add $session_id to database with all the parameters/variables you are using>
setcookie("session_id",$session_id);
setcookie("session_exp",time()+3600);

The just fail the cookie if $session_exp is expired. Also you can leave the expire cookie because you can store this information to DB.

Don't send plaintext in cookies, it just invites crackers to exploit your site.

pzijde at zs dot nl
27-Feb-2001 11:51

Here is a solution to set and check a cookie within 1 document:

<!-- img_stat.php -->
<?php
SetCookie ("test_id","Test",0,"/",".foo.com",0);
Header("Location: /img_stat2.php")
?>

<!-- img_stat2.php -->
<?php
header ("Content-type: image/gif");
$im = @ImageCreate (100, 50) or die ("not supported ...");
if ("$test_id" == "Test") {
 # The cookie is set, do your action
 $background_color = ImageColorAllocate ($im, 0, 0, 0);
} else {
 # Cookie is not set, do your action
 $background_color = ImageColorAllocate ($im, 255, 255, 0);
}
ImageGif ($im);
?>

<!-- HTML document -->
<img src="img_stat.php">

This example displays a black image when the cookie is accepted, otherwise displays a yellow image. But of course you can put every code you want.

NOTE: The cookie is not available in the HTML document during the first load, only in the second image file!!

I hope this will help ...

add a note add a note

<headers_sentHyperwave>
 Last updated: Sat, 05 Jul 2003
show source | credits | stats | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: HostNet Internet
Last updated: Sat Jul 5 04:10:53 2003 BRT