Re: Code to create a cookie in PHP [message #169828 is a reply to message #169825] |
Mon, 27 September 2010 19:55 |
Jerry Stuckle
Messages: 2598 Registered: September 2010
Karma:
|
Senior Member |
|
|
On 9/27/2010 3:18 PM, MikeB wrote:
> Now that I can delete cookies, I'd like to create cookies, but this code
> fails to create a cookie. Can anyone help me by telling me what is
> wrong, please?
>
> -MikeB
>
> <?php
> $name = "headercookie";
> $value = "MikeB set this in the header";
> $expire = time() * 24 * 60 * 60;
> $path = '/';
> $domain = "localhost";
> setcookie($name, $value, $expire);
> ?>
> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
> <html>
> <head>
> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
> <title> Set cookies</title>
> </head>
> <body>
> <?php
> if (isset($_COOKIE)) {
> echo '<br />First $_COOKIE<pre>';
> print_r($_COOKIE);
> echo "</pre>";
> } else {
> echo "<br />No cookies here!";
> }
> Echo "<br />Now setting my own cookie!";
> $name = "headercookie";
> $value = "MikeB set this in the body";
> $expire = time() * 24 * 60 * 60;
> $path = '/';
> $domain = "localhost";
> setcookie($name, $value, $expire);
> if (isset($_COOKIE)) {
> echo '<br />Second $_COOKIE<pre>';
> print_r($_COOKIE);
> echo "</pre>";
> }
> ?>
> </body>
> </html>
First of all, a cookie won't be available in the $_COOKIES array until
the browser fetches the next page. It is not available on the page you
set it (unless you already had a cookie with that name stored).
And your second setcookie() call will always fail. You cannot set a
cookie after headers are sent, and ANY output to the browser causes the
headers to be sent. You will see this error if your php.ini file has:
error_reporting = E_ALL // or E_ALL | E_STRICT
display_errors = on
As a side, you are never using the $domain value. The cookie will
belong to the domain you are requesting the page from - if that happens
to be 'localhost', it will belong to localhost.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex(at)attglobal(dot)net
==================
|
|
|