dousu8456 2019-07-28 21:29
浏览 120
已采纳

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

  • 写回答

1条回答

  • dongrong6235 2019-07-29 13:41
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能