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.
Последние статьи
- 01.03.26ИТ / Уроки PHP Уроки простыми словами. Урок 3. Все операторы PHP с примерами, с выводом работы кода на экран.
- 28.02.26ИТ / Уроки PHP Уроки простыми словами. Урок 2. Типы данных в PHP с примерами.
- 27.02.26ИТ / Уроки PHP Уроки простыми словами. Урок 1. Коротко о языке веб-программирования PHP. Основы синтаксиса.
- 26.02.26ИТ / Базы данных Ошибки при переходе с MySQL 5.6 на 5.7 и как их исправить - импорт дампа БД завершился ошибкой или не работает INSERT. Отключение строгого режима STRICT_TRANS_TABLES или использование IGNORE
- 31.01.26ИТ / Разное Конвертация офисных файлов DOC, DOCX, DOCM, RTF в форматы DOCX, DOCM, DOC, RTF, PDF, HTML, XML, TXT без потерь и изменения разметки
21248