How to Get and Send HTTP Headers Using PHP



PHP



In this article, we show how to get and send HTTP headers using PHP.

HTTP headers hold all sorts of information, such as the type of file that the document requested is, as well as the type of request that is made by the client.



How to Get HTTP Headers From the Server

So the first thing we'll show how to do is get headers from the server.

The following PHP code below shows how to get the accept and verb from the headers from the server.



For this page, running the above PHP yields the following result shown below.

Actual PHP Output


Accept: */*
Verb: GET



So you can see a lot of information from the above code.

$_SERVER is a superglobal array in PHP which allows us to be able to get a lot of information from the server. This includes HTTP headers information.

The $_SERVER['HTTP_ACCEPT'] array gets information such as the type of file the document requested is.

The */* shows that the Accepter header indicates support for every possible content type.

The verb is obtained through the array $_SERVER['REQUEST_METHOD']. There are several methods that can do used when communicating through HTTP. The GET method simply retrieves a page. The PUT method adds content to the requested page. The DELETE method deletes a resource from the requested page.

If you look at the above verb, it will be the GET method, because you clicked on the link to get to this page, which is a GET request. Any time you're simply retrieving a web page, such as clicking on a hyperlink, it is always a GET request made to the server by the browser.


How to Send HTTP Headers

Now we will show how to send HTTP headers, so that it can be sent from the server to the client.

The following PHP code below sends HTTP headers to a client.



So this code above uses the PHP header() function to send header information to the client.

This can be anything such as what is shown above.

In the first exaple, we send the type of file it is and we set the character set.

In the second example, we send the information that the page has not been found (if no page has in fact not been found).

Know that if you are sending out headers, such as shown in the code above, headers must be the first thing sent to a client. So it must be at the very top of a web page. It cannot, for instance, be in the body of the page. If it is, the code will be an error. It must be the very first thing of the web document.

So this is just a brief overview of how to get and send HTTP headers using PHP.


Related Resources

How to Create an XML Document with PHP

How to Parse an XML Document Using PHP

HTML Comment Box is loading comments...