Agreed that the setcookie command must be executed before any output to the browser. Also the header must be sent before any output.
I got a bit confused with a suite of php modules designed to allow a secure logon through the use of cookies which contain a username and an md5-hash of the username and a password. The setcookie command was something like the following:
setcookie("ckname",$username.":".md5($username.$password),$exp);
header(Location: $HTTP_REFERER);
$exp is set to the current time plus 1 hour.
However, whilst this code executes without error, and the $HTTP_REFERER variable returns control to the calling module, the cookie doesn't seem to get set.
I've been tearing my hair out for days with this. I'm new to PHP and some advice would be helpful. Is the above code PHP3 and non PHP compliant?
I actually got a working solution today, of the following form:
setcookie("ckname",$username.":".md5($username.$password),$exp);
echo '<head><title></title>';
echo '<meta http-equiv="REFRESH" content="0; URL=http://www.mytarget.web">';
echo '</head>';
This successfuly sets the cookie, whose value can be viewed in the variable $ckname (in the above example) and redirects the browser to my desired site, which contains php to verify the users right to view that site.
Whilst I am happy that this works, I would like to know why the first example doesn't.