Skip to content
Advertisement

PHP getallheaders() will automatically send a response if i try to get a non existent key

I tried to use the function getallheaders() in php which basically gets the headers of the request as an associative array. the strange thing is that when i try to get a variable from this array if the key does not exist in this array it will send a response to the user.

Here’s the sample Code

$headers = getallheaders();
$a = $headers["non_existing_key"];
echo headers_sent();

This will print 1 which means that headers were sent, or in other words i can no longer open a session for the user because session_start() will work only if headers were not sent yet.
i know that i can check the key with isset(), but this is just of curiosity.

Can someone help me why this is happening?.

Advertisement

Answer

If you have enabled error_reporting and display_errors your code will trigger:

Notice: Undefined index: non_existing_key

In order to display the error PHP needs to send output to browser because you can’t mix HTTP headers and output.

You can verify if a key exists with the usual techniques (pick your favourite):

$a = isset($headers["non_existing_key"]) ? $headers["non_existing_key"] : null;
$a = array_key_exists("non_existing_key", $headers) ? $headers["non_existing_key"] : null;
$a = $headers["non_existing_key"] ?? null;
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement