Amit Perez
Amit Perez

Reputation: 29

Php cookies not setting in whole website

On my site, I set cookies expire time until 30 days. This is working for me in the main directory, but not on a sub-directory,

this.php

<!DOCTYPE html>
<?php
$expire=time()+60*60*24*30; 
setcookie ("user","David", $expire);
//this works and outputs the cookies value
?> 
<html>
<head>
</head>
<body>
<?php
echo $_COOKIE["user"];
?>
</body>
</html>

files/this.php

<!DOCTYPE html>
<?php
<html>
<head>
</head>
<body>
<?php
echo $_COOKIE["user"];
//error:cookie is empty
?>
</body>
?>

Upvotes: 0

Views: 107

Answers (3)

Amit Verma
Amit Verma

Reputation: 41219

You can add / in set cookies, adding a / can solve your problem, this means cookies are available in the entire site.

this might help you

<?php
$expire=time()+60*60*24*30; 
setcookie ("user","David", $expire,"/");
//this works and outputs the cookies value
?>

Upvotes: 1

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146460

When you set cookies server-side the information is transmitted in HTTP headers. The manual warns about this:

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace.

If you are not getting an appropriate warning from PHP, please tweak your error reporting settings until you do.

Upvotes: 0

Rob W
Rob W

Reputation: 9142

Cookies should be set before browser output as they are part of the HTTP header.

See: http://php.net/cookies

If you're wanting immediate storage and recall, perhaps $_SESSION would be a better solution

Upvotes: 1

Related Questions