PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<headers_sent setrawcookie>
view the version of this page
Last updated: Sun, 18 Jul 2004

setcookie

(PHP 3, PHP 4 , PHP 5)

setcookie -- Spedisce un cookie

Descrizione

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

setcookie() definisce un cookie da inviare insieme alle altre informazioni di header. I cookie devono essere spediti prima di qualsiasi altra intestazione (questa è una restrizione dei cookies, non di PHP). E' necessario perciò chiamare la funzione setcookie() prima di qualsiasi tags, anche <html> o <head>.

Tutti gli argomenti della funzione eccetto name sono opzionali. Se viene passato alla funzione solo l'argomento name, il cookie registrato con quel nome verrà cancellato dal client su cui è archiviato. E' possibile sostituire gli argomenti che non si intende specificare utitlizzando una stringa vuota (""). Gli argomenti expire e secure che richiedono numeri interi, non possono essere omessi inserendo una stringa vuota, per questo scopo si usa (0). L'argomento expire è un normale intero Unix Timestamp ottenibile grazie alle funzioni time() o mktime(). secure sta ad indicare che il cookie dovrebbe essere trasmesso soltanto attraverso un collegamento sicuro di tipo HTTPS.

Errori comuni:

  • I cookie diventano disponibili soltanto dalla pagina successiva a quella che li ha generati, o dopo il ricaricamento di questa.

  • I cookie devono essere cancellati specificando gli stessi parametri con cui sono stati creati.

In PHP 3, chiamate successive di setcookie() nello stesso script sono eseguite in ordine inverso. Se state provando a cancellare un cookie prima dell' inserimento di un altro cookie, dovete creare il secondo prima della cancellazione del primo. In PHP 4, chiamate successive di setcookie() invece, sono eseguite secondo l'ordine di chiamata.

Alcuni esempi sul modo di spedire cookie:

Esempio 1. setcookie() esempi di spedizione/creazione

setcookie ("TestCookie", "Test Value");
setcookie ("TestCookie", $value,time()+3600);  /* aspira in 1 ora */
setcookie ("TestCookie", $value,time()+3600, "/~rasmus/", ".utoronto.ca", 1);

Gli esempi mostrano come cancellare i cookie introdotti nell'esempio precedente:

Esempio 2. setcookie() esempi di cancellazione

setcookie ("TestCookie");
// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", ".utoronto.ca", 1);
Per cancellare un cookie dovete assicurarvi che la data di scadenza del cookie sia già trascorsa, in questo modo il cookie verrà rimosso dal client.

Si noti che i valori salvati nei cookies sono automaticamente codificati per la trasmissione via URL (urlencoded) quando il cookie viene inviato, e che al momento del richiamo sono automaticamente decodificati e assegnati ad una variabile che ha lo stesso nome del cookie. Per vedere il contenuto di un cookie in uno script, si usa una di queste due sintassi:

echo $TestCookie;
echo $HTTP_COOKIE_VARS["TestCookie"];

Potete registrare array in un cookie usando la notazione degli array al posto del nome del cookie. Questo equivale alla spedizione di tanti cookie quanti sono gli elementi dell'array, ma si ha un vantaggio: quando il cookie è ricevuto, tutti i suoi valori sono ordinati in un singolo array che ha per nome il nome del cookie:

setcookie ("cookie[three]", "cookiethree");
setcookie ("cookie[two]", "cookietwo");
setcookie ("cookie[one]", "cookieone");
if (isset ($cookie)) {
   while (list ($name, $value) = each ($cookie)) {
       echo "$name == $value&lt;br>\n";
   }
}

Per saperne di più sui cookies, Netscape's cookie specification è la risorsa giusta http://www.netscape.com/newsref/std/cookie_spec.html.

Microsoft Internet Explorer 4 con Service Pack 1 non crea correttamente cookie che hanno il parametro path specificato.

Netscape Communicator 4.05 e Microsoft Internet Explorer 3.x sembrano utilizzare in modo errato i cookie quando path ed expire non sono specificati.



add a note add a note User Contributed Notes
setcookie
rgm
02-Sep-2004 09:35
Everyone should note that according to the HTTP/1.1 spec, the Location: header needs an ABSOLUTE URI.  You *can not* simply say:

     Location: foo.php

You need to specify the full URI, protocol, host, port (if not 80), and all.  For the info in the spec, check out:

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30
PHPCoder
25-Aug-2004 10:49
Sorry to disagree with Mr-Yellow, but in my testing, using Max-Age in a cookie header has the result of IE6 treating the cookie like a session cookie (doesn't store it as a file).  I don't doubt that Max-Age is a better method (gets around problems with users having invalid date/time clocks) but if IE6 doesn't treat it correctly then its not very useful.

Stick with the setcookie() function and you won't have this problem (and every browser in the universe is backward compatable for the cookie expires parameter).
mr-yellow at mr-yellow dot com
15-Aug-2004 04:14
Sorry Secure not Secure=1....

Instead of setcookie it would be much safer to use the new
better specs and send the following.

A 1 hour cookie is as follows:

header('Set-Cookie: TestCookie=something+from+somewhere; Max-Age=3600; Domain=.www.domain.com; Path=/; secure;');

To Delete a cookie set -1:

header('Set-Cookie: TestCookie=something+from+somewhere; Max-Age=-1; Domain=.www.domain.com; Path=/; secure;');

-Ben
mr-yellow at mr-yellow dot com
15-Aug-2004 04:05
I was wrong.

It's not the manual that is wrong.

It's PHP.

It uses specs from years ago. Still uses the Expiry header.

This code:
setcookie("TestCookie", $value, 3600);

Sents:
Set-Cookie: TestCookie=something+from+somewhere; expires=Thu, 01-Jan-70 01:00:00 GMT

Whereas if PHP was correctly coded it should send this:
Set-Cookie: TestCookie=something+from+somewhere; Max-Age=3600

I'd suguest NOT using the inbuilt cookie functions as they are
old and wrong. Instead roll your own cookie function which
sents the Max-Age parameter as "seconds till expiry" as this
fixes all problems described below.

All you need to do to correctly send up-to-date properly
coded cookies is send the following header before the
Content-Type.

Set-Cookie: Name=Value; Max-Age=Secs; Domain=.www.domain.com; Path=/; Secure=1;\n\n

Everything after Name=Value should be optional.

-Ben
fromphpnet at blaksaga dot com
22-Jun-2004 06:31
Although the documentation says passing an empty string or zero in the case of an integer to ignore an argument, it is incorrect.  You will want to pass NULL to bypass integer arguments such as expire or you will wind up with unwanted results.
nobody at nospam dot com
09-Jun-2004 03:36
If the user has cookies turned off (you can check for this by setting a cookie and then redirecting to PHP_SELF?seen=1, for example), you can make a crude intimidation with WWW-Authenticate.

Ask the user to enter any username or password, and if the username is not already taken, you can use the data sent by the browser on each page request as a crude form of session management (probably with the aid of databases), where the user name and password contribute to the SID.

Hope this helps
Bulk at bulksplace dot com
16-May-2004 05:15
With regards to what cptnwinky said about cookies being set on windows XP, and the need for a period (.) in the domain parameter.

I noticed that if you just leave the 'domain' parameter blank, PHP and XP then have no problem setting the cookie to localhost (or what ever computer name you are using), with out the need for a period, or a DNS suffix.

Example:

<?php setcookie('cookie_name', 'data', time() + 3600, '/', ''; ?>
adam at metrovanlines dot com
24-Mar-2004 12:47
This limitation is mentiones in the <a href=”http://wp.netscape.com/newsref/std/cookie_spec.html”> Netscape HTTP Cookies Preliminary Specification </a> above but I thought it might save someone some time if it was posted here. (I wasted almost a day about it, Serves me right for not RTFMing ...)

There are limitations on the number of cookies that a client can store at any one time. This is a specification of the minimum number of cookies that a client should be prepared to receive and store.

   * 300 total cookies
   * 4 kilobytes per cookie, where the name and the OPAQUE_STRING combine to form the 4 kilobyte limit.
   * 20 cookies per server or domain. (note that completely specified hosts and domains are treated as separate entities and have a 20 cookie limitation for each, not combined)

Servers should not expect clients to be able to exceed these limits. When the 300 cookie limit or the 20 cookie per server limit is exceeded, clients should delete the least recently used cookie. When a cookie larger than 4 kilobytes is encountered the cookie should be trimmed to fit, but the name should remain intact as long as it is less than 4 kilobytes.
cptnwinky
05-Mar-2004 09:03
I know that others have had problems with WinXP and cookies not setting. Someone here has already mentioned that the domain field must have at least one dot (.) in it. The problem therein lies with most home users leaving your host name as localhost. This is fine and dandy for most applications but setcookie() seems to not like it so here is my solution...

Right Click My Computer > Properties > Computer Name > Change > More

Once there change the part where it say's "Primary DNS Suffix of This Computer" to whatever you want, e.g. com, net,X,home,localdomain

Restart the computer and start putting comp-name.DNS Suffix

I hope this helps others who have struggled with this problem I know it bugged me for the longest time.
fran (at) bigeuniverse (dot) com
02-Mar-2004 08:02
message to trouby, below:

Applying the "two-dot rule" for domain settings, the following:
         .example.com    (like: (dot)example(dot)com)
will cover both example.com and www.example.com, as well as
any other {server}.example.com.
trouby at hotmail dot com
01-Mar-2004 10:30
I had the following problem, I was creating a stat script. Each user on my site will get an ID based on there browser configuration and their IP address. When the user pops on my website, the first time they will get:

<?php
// index.php
session_start();
if (!isset(
$_SESSION['user_id'])) {
  
header("Refresh: 1");
   print 
"<script language='javascript' src='tstat.js'></script>";
}
else
  print
"welcome";
?>

// tstat.js
document.write('<img src="http://www.example.com/make_id.php?var1=bla" />');

<?php
// make_id.php
session_start();
$_SESSION['user_id'] = trb_makeID();  // my own function which generates an ID (not important)
?>

Now let's say my site is www.example.com and when I enter the site for the first time, the javascript will be printed and that javascript will connect to my make_id.php, which will assign the variable 'user_id', now when the brower will refresh, the script will print 'welcome'.

This all worked for me, BUT there were user which had trouble entering my site, after spending one whole day researching what could be the problem, I noticed that they entered my site 'example.com' and the javascript will print an image to 'www.example.com' so those visitors had launched two sessions at the same time and that resulted in a constant refresh..

My solution was to set my own session cookies with a correct domain. example.com and www.example.com are to different values for your browser!
nick at acresource dot com
26-Feb-2004 08:50
For those of you who wish to have their user's use a more complicated password, this regular expression makes sure they use at least one number, one lowercase letter, and one uppercase letter. This may be inconvenient for your users, but it will provide a secure ground for md5 hash.

<?php

$string
= "banana";

if (!
preg_match('/^\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*$/', $string))
{
   echo
"That is not a valid password.";
}
else
{
   echo
"That is a valid password.";
}

?>

Enjoy.
16-Feb-2004 02:50
The note by: "apex at xepa dot nl" on  24-Nov-2003 06:59

"Another note on storing passwords .. don't use MD5 it's too weak."

I believe that your statement is a little off there, MD5 is not an encryption. It is a hash and is by far the hardest hash to crack. The reason you're probably saying that it's too weak is because chances are you are using regular words as passwords[Example: banana]. Thus: It's a snap to crack with a quick script. If you add in a script to force the user to have a certain length of characters and must contain a certain amount of numbers, you would be fine. MD5 is very widely available, and most people do not have access to change their PHP settings and add in modules.
Luis Hernandez
12-Feb-2004 06:27
As mentioned in a few other notes, if the client date earlier than the server, then you could find

setcookie("name", "value", time()-3600);

failing to clear the cookie, because the on the client's side an hour earlier than the server is still in the future. You could just keep increasing the amount you subtract from time(), but it's an ulgy solution. As far as I can tell, people haven't suggested using mktime (the doc mentions it's an option).

So, for example, you can instead execute

setcookie("name", "value", mktime(12,0,0,1, 1, 1990));

if you assume no user will have their clock set to be before 1990.
silasjpalmer at dot optusnet dot com dot au
06-Feb-2004 08:31
Here's a good way to check that the host browser accepts cookies. (this one works, trust me!)

It includes a P3P header, so that the cookies are not blocked by IE6, unless the user has explicitly requested that cookies be blocked.

It uses a query string to see if the page has been re-loaded, which gets around the "cookie is only visible after refreshing the page" problem. It also preserves any existing query strings, so will still work if you include it on a page like "cookiesetter.php?product=milk&price=3.50"

testcookie.php

<?php

header
("P3P: CP=\"ALL DSP COR NID CURa OUR STP PUR\"");

$nocookies = false;
$reloaded = $_GET["ckset"];
$url = $_SERVER[PHP_SELF];
$querystring = $_SERVER[QUERY_STRING];

$querystring = str_replace("ckset=ok", "", $querystring);

setcookie("check_cookie", "on", time()+(1000000));
if (
$reloaded == "" and !isset($check_cookie)) {
   echo
"<META HTTP-EQUIV=\"refresh\" CONTENT=\"0;URL=http://www.naturalanimalcare.com/" .           

  
$_SERVER[PHP_SELF] . "?ckset=ok" . $querystring . "\">";
   exit;
   }

else {
   if (!isset(
$check_cookie)) $nocookies = true;

   }

?>

To use this, save it as "testcookie.php" and then the page you want to test cookies in would go something like this ...

<?php
include "testcookie.php"; // Test for cookies

// Other setcookie commands go here...
//
// Headers, layout, etc go here...
//
// Body text ...
If ($nocookies) {
           echo
"Your browser is not accepting cookies.<br>
             Please turn them on or update your browser"
;
           }
else {
           echo
"Your browser is accepting cookies";
          
// Rest of the page goes here...
          
}

// Footers, etc.

?>
shrockc^inhs^org
23-Dec-2003 04:10
NOTE: this is related to an earlier note, but contains a little more detail

Using IIS3/4/5?, using sessions?  using automated logins?

Guess what?  When running php as a CGI in IIS, IIS will
remove set-cookie headers if there is also a 302 status
(Location: redirect) header.

Why do you care?
Ever need to log in a user in the first page that a user sees
of your site?  Well, you can't if you use IIS3/4/5 and any CGI
like Perl and PHP.

Here is the kb article:
http://support.microsoft.com/support
/kb/articles/q176/1/13.asp&NoWebContent=1

Guess what the workaround is:
rename 'php.exe' to 'nph-php.exe'
php@undiluted dot org
28-Nov-2003 06:34
A little thing with IE 6 and cookies.  I was fighting until I found a note on this on another site.  So I figured I would put it here because this is the first place I go for information on php.  So here it goes.

If the timezone, or time for that matter on the server that php is on is not set properly, IE 6 for some reason will care about that and not set the cookie.  Just something to look out for.
frymaster
26-Nov-2003 01:40
a note about cookies, subdomains and poorly formed domain names: for a cookie to correctly set itself to be read across multiple subdomains it *must* contain at least one 'dot'.

this is important if you are developing an application on a test server on your local network and are accessing it by a domain set in either /etc/hosts or the lmhosts file. if the domain you have chosen is not well-formed, your cross subdomain cookies will not work.

example:
your /etc/hosts file looks like this

192.168.1.1    testserver  site1.testserver  site2.testserver

you will not be able to create cookies across the subdomains. to rectify this situation, make sure that your hostnames have a 'dot' in them, as so:

192.168.1.1    testserver.foo  site1.testserver.foo  site2.testserver.foo
apex at xepa dot nl
25-Nov-2003 03:59
[Editor's note: ... or simply use sessions. You can't be sure that the visitor will use the same IP the next visit. Not even on the next request (thanks to proxy servers)]

Note on setting cookies allowing access to sites:

If you are not using something "personal" from the computer that you are sending the cookie too watch out.  Via javascript it is possible to steal cookies from other users.  Thus allowing the stealer to login to your site as another user that might not have access otherwise.  Try to add something like the user's ip in the cookie and allowing access from that ip only with the stored cookie data.
andres at uprm dot edu
28-Oct-2003 06:48
When setting a cookie with multiple sub-domains, do not append the leading dot to the domain (set the domain as "example.com"). This works in Internet Explorer (tested with IE6 in Windows and IE5 in Mac), Mozilla (tested in 1.5) and Mozilla Firebird (tested in 0.7).

When we appended the dot, we were unable to read cookies from other subdomains.
mastabog<a>hotmail<d>com
24-Oct-2003 03:51
There was a post earlier saying that there is a workaround of the fact that cookies are only available after a refresh.

For newcomers, cookies are ONLY available after you change the page that has set a cookie. In the new page you can see the cookie that was set  accessing the $_COOKIE array.

The workaround that guy proposed sothat you see the cookie in the same page where you set it was both to make a call to setcookie(), which sets the cookie into the browser for the pages to follow, AND to modify manually the $_COOKIE array.

NEVER do that if you want to work with real cookies. Sure modifying the $_COOKIE array is possible (its just another global array variable from the language point of view) but if the cookie is not set then you will still have a value in your $_COOKIE array (cus you set it manually) but no real cookie in your browser, and on the pages to follow there won't be any cookie. Also its not a "nice" way of programming :) ... predefined global arrays usually should not be modified manually.

Try to always avoid that "workaround". Use cookies properly like they were ment to.

Cheers,
Bogdan
contact at linterweb dot com
22-Oct-2003 08:10
With some browser IE 6.0, you can not put a cookie, if the serveur is not the server real name.
It s to solve the problem
if($_SERVER['HTTP_HOST']!=$_SERVER['SERVER_NAME'])
{header ("location:http://".$_SERVER['SERVER_NAME']." ".$_SERVER['REQUEST_URI']."");
exit();}
alefor at gmx dot de
21-Oct-2003 05:49
Cookies will not stored in IE6 if the server hostname
contains '_' (underscore).
I don't know if this applies to zone domain names too.
Examples are pc_smith, lp_smith, host_1.
Jörg Aldinger
01-Oct-2003 01:13
When using your cookies on a webserver that is not on the standard port 80, you should NOT include the :[port] in the "Cookie domain" parameter, since this would not be recognized correctly.
I had the issue working on a project that runs on multiple servers (development, production, etc.). One of the servers is running on a different port (together with other websites that run on the same server but on different ports).
brewthatistrue at plzYnoAspamHorOevilO dot com
23-Sep-2003 10:25
in response to
soreman at abv dot bg
11-Apr-2003 03:26 (i'm glad i didn't waste time wondering why setcookie stopped working when i switched from apache)
to get around that iis problem, i changed from

Header("Location: $WEB_ROOT/index.php");

to

header("Refresh: 0; URL=$WEB_ROOT/index.php");

worked like a charm.

( inspred by nalenb's comment at http://e107.org/comment.php?298 - got the proper syntax from http://www.desilva.biz/php/phprefresh.html )
Eugene at php at burtsev dot com
19-Sep-2003 11:11
This is my way of finding out if cookies are on and if session ID needs to be sent as URL:

<?PHP

session_start
();
$self = $_SERVER['PHP_SELF'];
if (!
$_GET['sID'] && !$_SESSION['cookie'])
{

  
$sID = session_id();
  
header ("Location: $self" . "?sID=$sID");
   exit;
}
if (!
$_SESSION['cookie']){
if (
session_id() == $_GET['sID']) {
$_SESSION['cookie'] = "1";
header ("Location: $self");
exit;
} else {
$_SESSION['cookie'] = "0";
session_id($_GET['sID']);
}
}
print
"Result is: " . $_SESSION['cookie'];

?>

I call it ones during logon, but don't see any harm in calling it with page. 

Cheers

Eugene
george at whiffen dot net
19-Sep-2003 03:52
WARNING:  You probably do NOT want the default setting for cookie path!

TIP: Explicitly set cookie's path to "/" unless you are ready for unexpected results i.e.

Use this: setcookie('mycookie','myvalue',0,'/')
Not this: setcookie('mycookie','myvalue')

EXPLANATION: Browsers will store separate cookies for different path settings and you may not get the one you want/expect.  In particular, you may think you have deleted a cookie only to find that your script is still being sent a cookie with the same name but a different path.

If you don't specify a path the browser will create different cookies depending on what directory your script runs in.  Move your script and you get a new cookie.  Delete the new cookie and the old one is still there.

To make it worse, you can also have different values for the same path if you used different syntaxes i.e. with/without a trailing slash e.g.
setcookie('mycookie','myvalue',0,'/subdir')
setcookie('mycookie','myvalue',0,'/subdir/')
These are two different cookies, which can have different values.  Deleting or changing one has no effect on the other.

Similarily, from a top level script, these are two different cookies:
setcookie('mycookie','myvalue')
setcookie('mycookie','myvalue',0,'/')

That means if you just have a plain path-less setcookie() in a top level script which you then move to a sub-directory, you will get two different cookies.  The original top-level one is then hard to get rid of:

You cannot use: setcookie('mycookie','myvalue')
This will create a new cookie with path set to the sub-directory path

Nor can you use: setcookie('mycookie','myvalue',0,'/')
This will create a new cookie with path set to '/', not to blank

Nor can you use: setcookie('mycookie','myvalue',0,'')
This will be treated as an alternate syntax for setcookie('mycookie','myvalue')

You must use: setcookie('mycookie','myvalue',0,' ') // path set to space
This will change a cookie set in a top-level script with no path.

It's not just a matter of cookies hanging about when you thought you deleted them, the value you will get when the same cookie is set with different paths seems to be just the last one set, not the most specific one.

Sorry if I'm not explaining this well, but that's the point!  Unless you "hard-code" your cookie path to /, you are very likely to get complications sooner or later ;).  If, as I was, you are trying to change a top-level insecure cookie to a sub-directory secure cookie, it's a nightmare to work out what's going on and whether or not you've got rid of any old insecure cookies.
dave at fubra dot com
09-Sep-2003 09:36
There are several characters that dont work correctly if part of the cookie name, I in particular ran into problems using = as part of the cookie name ie/

setcookie('dE4fR=', $foo);

this was as a result of base64_encode() ing a variable to use as the name. The cookie was being set fine but the = is stored as a little square character in the cookie which prevent proper retreival.

The solution for me was to use md5() instead of base64_encode() but any other method which avoids the = sign should also solve the problem
thomas at proton dot mine dot nu
30-Jun-2003 01: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 11: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
soreman at abv dot bg
12-Apr-2003 12: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.
oz at austdesign dot co dot uk
07-Mar-2003 02: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;
}

----------------
Lebbeous Weekley
06-Feb-2003 05: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.
peterg at NOSPAM dot mildewhall dot com
30-Jan-2003 06: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 09: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
mleer at sp dot nl
19-Dec-2002 11: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!
public at macfreek dot nl
13-May-2002 05: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 02: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 09: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
06-Dec-2001 12: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/

<headers_sent setrawcookie>
  Last updated: Sun, 18 Jul 2004
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2004 The PHP Group
All rights reserved.
This unofficial mirror is operated at: http://php.libero.it/
Last updated: Mon Oct 11 03:15:27 2004 CEST