简体   繁体   中英

PHP, setcookie function doesn't work

I have the code:

$user_cookie = hash("sha512",$username);
$salt1 = hash("sha512", rand() . rand() . rand());
setcookie("c_user", $user_cookie, time() + 12 * 60 * 60, "/");
setcookie("c_salt", $salt1, time() + 12 * 60 * 60, "/");

On localhost it works fine but on webserver doesn't work. I can't understand, why? This code is included in if and all other code from this if works but this-no. If I write echo $user_cookie."\\n".$salt1; I have these values!

According to setcookie() documentation

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 and tags as well as any whitespace.

I had the same problem using cookies, the code was working fine on the localhost but doesn't work on the webserver, beside that headers doesn't work properly too. I started debuging by adding a temporary piece of code to my file:

header("Location: /test");

I found that the code below works properly

header("Location: /test");
include("myfile.php");

while the other one doesn't :

include("myfile.php");
header("Location: /test");

After all, I figured out that there was a space after ?> in myfile.php

How to fix "Headers already sent" error in PHP

This works for me to set a cookie for an hour from now for my local dev environment running EasyPHP and on a GoDaddy hosted server for several domains:

setcookie($cookie, $value, time()+3600, '/', '127.0.0.1', true);

Try adding your domain (the 5th parameter/127.0.0.1) and I would recommend setting the secure boolean to true as well

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM