Reputation: 29
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
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
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
Reputation: 9142
Cookies should be set before browser output as they are part of the HTTP header.
If you're wanting immediate storage and recall, perhaps $_SESSION
would be a better solution
Upvotes: 1