简体   繁体   中英

How to get Apache HTTP response code (or first line of server response) with PHP

How can I get the first line of the servers' HTTP response (Apache2 in my case) for use in my PHP scripts? For example:

HTTP/1.1 200 OK
HTTP/1.1 404 Not Found
Etc.

Or better yet, get just the HTTP response code that my server sends to the client.

To my surprise, $_SERVER doesn't have it. http_response_code() seems to only get the response code if it's first been set by PHP. apache_response_headers() doesn't seem to have it. get_headers() seems like it would require an extra step/connection (correct me if I'm wrong).

If I set ErrorDocument 403 /index.php in httpd.conf, I can use $_SERVER["REDIRECT_STATUS"] to get the response code from PHP, but is there another way?

EDIT:

Just to be clear, I find it odd that $_SERVER returns almost every bit of data except for the first line of the response or the response code. Maybe it's a general limitation between the HTTP protocol/server technology/PHP? Maybe I shouldn't be trying to access this info in my PHP scripts?

UPDATE: NO IT'S NOT POSSIBLE Unless you proxy your own requests. Send your request to a Public facing URL and then redirect them to an internal variant and you get to see the headers in the process. But it's not an easy feat and performance taxing also. Or you can write a Http Server extension and see where that takes you :)

Example:

  • request comes to /page.html
  • you append ?proxy=true and forward to /page.html?proxy=true
  • attempt to load new URL internally forwarding the original request to you internal handler
  • check in your internal handling for all $_GET['proxy'] === 'true' requests come from local IP
  • if you have a proxy === true then handle this the usual way
  • /page.html gets data from /page.html?proxy=true
  • logs headers
  • forwards data back to original client
  • (not very easy and performance taxing if done wrong)

FIRST ATTEMPTS AT ANSWERING

http://php.net/manual/en/function.headers-list.php - may be this one?

But this works for the headers you are about to send...

register_shutdown_function(function(){
    // Headers are really sent here, do some comparison
    var_dump(headers_list());
});

.htaccess variant that directs all missing files to index.php.

RewriteEngine on
#If handler file is missing, pull index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.php [L,NC]

Try this.

Are you asking for the response code of a remote host or the local machine? In the first case you could "ping" the machine using a CURL request with the header option set and retrieve various settings of the response header.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM