php setcookie没有错误

I'm trying to set cookies with PHP. I wrote a login script that checks data received from the user with database data and then if data matched, it sets a cookie that stores username and password to be used in the next two hours. This is a PHP script to handle an HTTP POST request and output JSON to be used in a react app.

I used ob in my code and I am sure that there are no headers sent before setting cookies.

This is how my code looks like.

    <?php
        ob_start();

        function cook($user, $pass, $time){
            setcookie("user", $user, time() + $time, "/", "localhost", 0);
            setcookie("pass", $pass, time() + $time, "/", "localhost", 0);
        }

        header('Content-Type: application/json');

        //login code(receive data, check password, ...)

        cook($user, hash("sha512", $pass), 7200);

        $output = //my code output object

        echo json_encode($output);

        ob_end_flush();

There is no errors and exception.

UPDATE: I am using cross-origin request. My client is on localhost:3000 and PHP scripts are running on localhost:8080

dongyuan1984
dongyuan1984 还使用/etc/hosts从localdev.com添加了重定向到localhost。那没起效。
大约一年之前 回复
doumi6685
doumi6685 那么如何在不使用cookie的情况下设置自动登录呢?
大约一年之前 回复
doudong7256
doudong7256 有没有办法在我的localhost上解决这个问题?
大约一年之前 回复
duan205571
duan205571 那不行
大约一年之前 回复
duananyantan04633
duananyantan04633 此外,将密码存储在cookie中也不是一个好习惯,即使它们是经过哈希处理的。
大约一年之前 回复
douyan2680
douyan2680 除非浏览器与Web服务器位于同一台计算机上,否则localhost将无法运行。这需要是您访问Web服务器的域。或者你可以不指定它。
大约一年之前 回复
ds261634878
ds261634878 为什么要在cookie中存储密码/哈希?
大约一年之前 回复
doushenyi9104
doushenyi9104 文档清楚地表明“没有输出将被发送(除了标题)”所以这不完全正确。在标题前拨打你的电话。
大约一年之前 回复

1个回答



问题已解决。 实际问题来自邮寄请求。 它没有发送带有请求的凭据。
首先,我和Credentials一起坐了下来。 然后更改了一些标头以接受我的apache配置中的凭据,如下所示:</ p>

 标头集Access-Control-Allow-Origin“http://localdev.localdev.com:3000”

Header set Access-Control-Allow-Headers“Content-Type”
Header set access-Control-Allow-Credentials“true”
</ code> </ pre>

注意:我还添加了 我在评论中提到的/ etc / hosts中我的127.0.0.1的域。
我知道这不是一个PHP问题。 但这可能会有所帮助。</ p>
</ div>

展开原文

原文

Problem fixed. The actual problem was from the post request. It did not send the credentials with the request. First, I sat withCredentials to true. Then changed some headers to accept credentials in my apache config like this:

Header set Access-Control-Allow-Origin "http://localdev.localdev.com:3000"
Header set Access-Control-Allow-Headers "Content-Type"
Header set Access-Control-Allow-Credentials "true"

Note: I also added a domain for my 127.0.0.1 in /etc/hosts as I mentioned in comments. I know that is not exactly a PHP problem. But this may help.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐