简体   繁体   English

PHP,setcookie 功能不起作用

[英]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 和此 if 中的所有其他代码中,但 this-no。 If I write echo $user_cookie."\\n".$salt1;如果我写 echo $user_cookie."\\n".$salt1; I have these values!我有这些价值观!

According to setcookie() documentation根据setcookie()文档

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. setcookie() 定义了一个与其余 HTTP 标头一起发送的 cookie。 Like other headers, cookies must be sent before any output from your script (this is a protocol restriction).与其他标头一样,cookie 必须在脚本的任何输出之前发送(这是协议限制)。 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.我在使用 cookie 时遇到了同样的问题,代码在本地主机上运行良好,但在网络服务器上不起作用,此外标题也无法正常工作。 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毕竟,我发现 myfile.php 中的?>后面有一个空格

How to fix "Headers already sent" error in PHP 如何修复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:这适用于我从现在起为运行 EasyPHP 的本地开发环境和多个域的 GoDaddy 托管服务器设置一个小时的 cookie:

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尝试添加您的域(第 5 个参数/127.0.0.1),我建议也将安全布尔值设置为 true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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