It seems I don't really understand the handling of the PHPSESSID
cookie in PHP and in browsers. I don't understand when the browser does store the cookie and send it back and when the browser doesn't store and doesn't send it back. I tried the following code with the PHP's local server: php -S localhost:8900 ./test.php
With the first example I get the cookie correctly on the second request. So, on the first request print_r
prints an empty array, on the subsequent request it prints the array with the session cookie:
<?php
print_r($_COOKIE);
if (!isset($_COOKIE['PHPSESSID'])) {
session_start();
echo "Starting a session<br/><hr/>";
}
After the first request: Array ( ) Starting a session
After the second request: Array ( [PHPSESSID] => 4f5eh40sjlul4ggs86evee0s73 )
But with the following code, I never get the PHPSESSID
cookie in the serverside code. I can see that the server sends the cookie back in the response header, as in the first example, but the browser doesn't seem to store it and so the browser doesn't send the cookie in the second subsequent request to the server:
<?php
print_r($_COOKIE);
if (!isset($_COOKIE['PHPSESSID'])) {
session_start();
echo "Starting a session<br/><hr/>";
}
else {
echo "Destroying a session<br/>";
setcookie('PHPSESSID', '', time() - 3600);
}
The problem is that I'm working on session handling on a big PHP BE and I'm trying to figure out how does the session in PHP work, especially with the PHPSESSID
cookie.
So, I really want to understand this part of the session handling.
For each request, your code alternates between setting and destroying sessions
Since you said:
… every request goes through your script.
So when you type
http://localhost:8900/
into your browser's address bar it requests/
and creates the session and then requests/favicon.ico
and deletes the cookie. When you reload the/
it repeats.