prjmbq
Last Updated: February 25, 2016
·
6.668K
· dlion
28864ba1e7e4490c3e5e97e095d4b6c7

Set a cookie on localhost

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

setcookie("name","value",false,"/",false);

If you try to set a cookie with:

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

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

Say Thanks
Respond

4 Responses
Add your response

627

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):

<?php
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 ·
628
28864ba1e7e4490c3e5e97e095d4b6c7
over 1 year ago ·
629

@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 ·
630
28864ba1e7e4490c3e5e97e095d4b6c7

@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);
else
setcookie("name",'value',time()+3600);
And this work perfectly ;)

over 1 year ago ·