r/PHPhelp • u/trymeouteh • Mar 14 '25
Solved Get all headers in request without sending out any headers?
This there a way in PHP to get all the headers in the request (From the browser) before sending any headers?
I want something like getallheaders() but does not cause the headers to be sent. In the example code below, it will throw an error due to the headers already being sent once it reaches line 7.
<?php
print_r(getallheaders());
$isHeadersSentA = headers_sent();
header('Content-type: text/html');
$isHeadersSentB = headers_sent();
echo 'Hello World';
echo '<br>';
$isHeadersSentC = headers_sent();
echo '<br>';
echo '$isHeadersSentA = ' . $isHeadersSentA;
echo '<br>';
echo '$isHeadersSentB = ' . $isHeadersSentB;
echo '<br>';
echo '$isHeadersSentC = ' . $isHeadersSentC;
1
Upvotes
7
u/Full_Sea_3888 Mar 14 '25
i think what maybe happening here is that your print_r is being processed before the header. So, the browser expects the headers to be the first thing it sees, but instead it's seeing the print_r. try moving the header command above your print_r and see if that helps.
1
u/rainydaysforpeterpan Mar 14 '25
Instead of getallheaders(), you can retrieve request headers manually from $_SERVER without sending any headers:
1
u/Decent-Economics-693 Mar 16 '25
In short, there has to be zero output produced by your script, before you send any header.