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
- 03.04.24IT / Уроки PHP Уроки простыми словами. Урок 3. Все операторы PHP с примерами, с выводом работы кода на экран.
- 02.04.24IT / Уроки PHP Уроки простыми словами. Урок 2. Типы данных в PHP с примерами.
- 02.04.24IT / Уроки PHP Уроки простыми словами. Урок 1. Коротко о языке веб-программирования PHP. Основы синтаксиса.
- 09.11.23IT / Database Errors when migrating from MySQL 5.6 to 5.7 and how to fix them - database dump import failed with an error or INSERT does not work. Disabling STRICT_TRANS_TABLES strict mode or using IGNORE
- 08.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