PHP Web Fundamentals
Reading an HTTP Header
Problem
You want to read an HTTP request header.Solution
For a single header, look in the $_SERVER superglobal array:// User-Agent Header
echo $_SERVER['HTTP_USER_AGENT'];
For all headers, call getallheaders():
$headers = getallheaders();
echo $headers['User-Agent'];
Discussion
HTTP headers allow the browser (or any application) to pass supplementary information about the request. For example, Content-Type to describe the body (Did you send a web form or JSON?), Accept-Language for a list of preferred languages (Do you want that in Canadian English or Canadian French?), and User-Agent (What’s the name and description of the browser?).Sometimes your web server will automatically process these headers and act accordingly, particularly when it comes to low-level details about the request, such as serving data from a cache or (de-)compressing the data. Other times PHP will parse specific headers.
But there are times when you want to read a specific header within your code. One example is parsing the ETag header to see if the version the client has is the same as the one that’d be sent back.
In these cases, reference the $_SERVER superglobal array. PHP namespaces HTTP request headers by prefixing HTTP_ before the header name. It also uppercases all header names to make them easy to find. (This is legal because header names are caseinsensitive.)
So, the ETag header, if sent, will be at $_SERVER['HTTP_ETAG']. If the field munging is aesthetically displeasing, you can also find it at getallheaders()['Etag'].
No comments:
Post a Comment