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.

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog