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
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.