Recently, I came across a weird contrast while developing a PHP script.
The point is, I want to send an HTTP response status code to another page using the global $_SESSION variable. Then on the destination page, I will send this HTTP response status code to the browser by using the header() method. It doesn't matter what the HTTP response status code is. For example we consider here "422 Unprocessable Entity".
So, easily we write our script:
file1.php: (the source file)
<?php
session_start();
$_SESSION['xyz'] = "422 Unprocessable Entity";
header('Location: file2.php');
file2.php: (the destination file)
<?php
session_start();
header("HTTP/1.1 " . $_SESSION['xyz']);
var_dump($_SESSION['xyz']);
unset($_SESSION['xyz']);
After entering URL example.com/file1.php, we will be transferred to the destination (example.com/file2.php) without any problems. In the browser console (Network tab) we will see a 422 error. No error_log file has created and also the output content of the page is:
string(24) "422 Unprocessable Entity"
Everything looks good. But the problem is, if you use https://httpstatus.io/ to check the correctness of the header sent, in addition to creating an error_log file on your server, you will encounter the following output:
Which is quite confusing. Moreover, the content of error_log file is:
[02-May-2021 22:21:13 UTC] PHP Warning: Undefined array key "xyz" in /www_root/file2.php on line 3
[02-May-2021 22:21:13 UTC] PHP Warning: Undefined array key "xyz" in /www_root/file2.php on line 4
which means that the variable $_SESSION['xyz'] has not set.
I tried to debug the script simply by modifying file2.php:
<?php
session_start();
header("HTTP/1.1 422 Unprocessable Entity");
var_dump($_SESSION['xyz']);
unset($_SESSION['xyz']);
Then, the problem was solved strangely:
Now I want to ask the question, is the basis of my method (passing HTTP response status code to another page) correct? If so, why do I get error? Does the header() method execute in PHP before receiving $_SESSION variables? What is the execution schedule of these two functions? Thank you for your help.


