HTTP response (server) headers - how to send, receive or remove them in PHP
HTTP headers are very important for the exchange of information between the browser and the server. They are of two types - request headers and response headers. This article covers response headers.
How to send HTTP response headers
Since the response headers are sent by the server, it is necessary to use programming language tools, for example, PHP facilities . It has special functions for working with headers. To send the header - header function.
You can only send headers if no data has been sent yet. Before calling this function, there should be no HTML tags, empty lines, etc., including in include files. That is, the headers are sent first, and then the data itself.
Examples of sending headers to PHP to the browser:
header ('HTTP / 1.1 404 Not Found');
header ('Status: 404 Not Found');
header ('Location: https: // example.com');
How to get HTTP response headers
The following functions are available for this:
- get_headers - returns all headers from the server response to the HTTP request;
- apache_response_headers - Returns a list of all Apache HTTP response headers;
- http_response_code - gets or sets the HTTP response code;
- headers_list - Returns a list of headers submitted (or ready to send).
You can also use the CURL library. How to get response headers using CURL? Example:
if ($ curl = curl_init ('https://example.com')) {
curl_setopt ($ curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ curl, CURLOPT_NOBODY, true);
curl_setopt ($ curl, CURLOPT_HEADER, true);
$ out = curl_exec ($ curl);
echo $ out;
curl_close ($ curl);
}
How to remove HTTP response headers
Headers can be removed using a special function - header_remove . First you need to check if headers have been sent:
if (! headers_sent ()) {
header_remove ('Content-Type');
}
As you can see from the article, it is very easy to work with HTTP response headers on the server side.
Latest articles
- 09.07.22IT / Misc Convert office files DOC, DOCX, DOCM, RTF to DOCX, DOCM, DOC, RTF, PDF, HTML, XML, TXT formats without loss and markup changes
- 07.07.22IT / Safety How to protect PHP, JS, HTML, CSS source code - obfuscation, minification, compression and encryption
- 06.07.22IT / Safety Connection not secure, problem with Lets Encrypt - how to fix expired 09/30/2021 DST Root CA X3, remove it manually and install ISRG Root X1. Example on MS Windows 7
- 08.07.21IT / Misc How to make a free translation for a website without an API, translate documents in Google Translate
- 06.07.21IT / Misc How to make a subscription button on a website, a subscriber base and automatic mailing