Last Updated: February 25, 2016
· dlion

Set a cookie on localhost

If you want set a cookie with php on your local server (localhost)
you can do this with:


If you try to set a cookie with:


this doesn't set a cookie if you use it on your local server.

4 Responses
Add your response


I'd be curious to know your motivations behind the top method.

From the PHP manual:

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

With the top one, you're setting what should be an integer and a string ($expire and $domain respectively) to a boolean.

A quick test script (using your non-working example):

if ( ! isset( $_COOKIE['testing'] ) ) { 
    setcookie( 'testing', 'value', time() + 3600 );
    header( 'Location: cookie.php' );
else {
    print '<pre>' . var_export( $_COOKIE, true ) . '</pre>';

Result (on localhost):

array (
    'testing' => 'value',

Perhaps there is another reason the cookie isn't working, given the cookie should be saved on the client (irrespective of whether or not the client is the same host as the server.)

over 1 year ago ·

@dlion Curious indeed. I'd say swap browsers but being an RFC, there's no guarantee that other browsers won't adopt these security recommendations at some point.

Thanks for clearing that up.

I wonder if the cookie needs to be added exactly as above, or if the two false values could be changed to 0 and '' respectively to achieve the same result?

over 1 year ago ·

@michaeldyrynda I'm sorry but I don't know, I didn't try.
In the future I'll do it.
Now I'm working with:
if($SERVER['HTTPHOST'] == "localhost")
setcookie('name', 'value',false,"/",false);
And this work perfectly ;)

over 1 year ago ·