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 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办