I've actually spent a few hours looking this up but so far haven't found anything that worked in my case (as I had already cleared the bases, at least as far as I could tell). Here's the situation:

I've written up a script that writes a cookie to the system. After fiddling with it and learning how it all works, I got it to work flawlessly... for Localhost. I finished up the rest of the site and was happy that everything works great! But then I moved the site to a web host. The site is still great, except for one large problem: cookies are never written. I can not figure out why, and have even 777'd the files (they are still on a "private address" for now) and they still won't write the cookies. So here's some pseudocode for you. Hopefully someone can figure out where I'm going wrong, or what I need to be checking out.

if (isset($_GET['name']))
{ 
$_COOKIE["name"] = $_GET['name'];
$name = $_GET['name'];
$cexp = time()+60*60*24*3650;
setcookie("name", "$name", $cexp, "/");
}

So one of the things people said to do is to add the URL after the path variable. I did this as well (using the format ".example.com") and that has had no impact.

What confuses me is that even now, this code works flawlessly on the local host (and I can see the cookies written to the domain "localhost") but on the hosted server I'm having no luck at all.

Any help would be much appreciated, and I'll also answer any questions to the best of my ability.

Thanks in advance!


Edit: Thank you all so much for helping with this! I'm new to cookies, so this was unexplored territory. I assumed if it worked on my own server, it should work on an actual host as well. And we all know what happens when we assume...

So for anyone else with a similar problem, here would be the proper code:

if (isset($_GET['name']))
{ 
$name = $_GET['name'];
$cexp = time()+60*60*24*3650;
setcookie("name", "$name", $cexp, "/");
$_COOKIE["name"] = $_GET['name'];
}

Alternatively you could leave out the last line. I have that there as a fallback so that the data is still available without a page refresh (as it deals with information that I want to stay in a text box). Also, this stuff HAS to be at the top of the page. A big problem I had was going with a three-part site: Header, Main and Footer php files, each in their own div. Cookies have to be dealt with prior to even starting the div's, so I need to reorganize my code now.

Thanks again all!

有帮助吗?

解决方案

Try this:

session_start();

$test = "cheese";
$cexp = time() + (60*60*24*3650);

setcookie("test", $test, $cexp, "yourdomain.extension");

if(isset($_COOKIE["test"])) {
    echo $_COOKIE["test"];
}
else {
    echo "Refresh Page!";
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top