header
header() используется для отправки HTTP заголовка. В » спецификации HTTP/1.1 есть подробное описание HTTP заголовков.
Помните, что функцию header() можно вызывать только если клиенту еще не передавались данные. То есть она должна идти первой в выводе, перед ее вызовом не должно быть никаких HTML тэгов, пустых строк и т.п. Довольно часто возникает ошибка, когда при чтении кода файловыми функциями, вроде include или require , в этом коде попадаются пробелы или пустые строки, которые выводятся до вызова header() . Те же проблемы могут возникать и при использовании одиночного PHP/HTML файла.
/* Этот пример приведет к ошибке. Обратите внимание
* на тэг вверху, который будет выведен до вызова header() */
header ( ‘Location: http://www.example.com/’ );
exit;
?>
Список параметров
Существует два специальных заголовка. Один из них начинается с «HTTP/» (регистр не важен) и используется для отправки кода состояния HTTP. Например, если веб-сервер Apache сконфигурирован таким образом, чтобы запросы к несуществующим файлам обрабатывались средствами PHP скрипта (используя директиву ErrorDocument), вы наверняка захотите быть уверенными что скрипт генерирует правильный код состояния.
Другим специальным видом заголовков является «Location:». В этом случае функция не только отправляет этот заголовок броузеру, но также возвращает ему код состояния REDIRECT (302) (если ранее не был установлен код 201 или 3xx).
header ( «Location: http://www.example.com/» ); /* Перенаправление броузера */
?php
/* Можно убедиться, что следующий за командой код не выполнится из-за
перенаправления.*/
exit;
?>
Необязательный параметр replace определяет, надо ли заменять предыдущий аналогичный заголовок или заголовок того же типа. По умолчанию заголовок будет заменен, но если передать FALSE , можно задать несколько однотипных заголовков. Например:
Принудительно задает код ответа HTTP. Следует учитывать, что это будет работать, только если строка string не является пустой.
Возвращаемые значения
Эта функция не возвращает значения после выполнения.
Список изменений
Версия | Описание |
---|---|
5.1.2 | Стало невозможно отправлять более одного заголовка за раз. Это сделано для защиты от атак, связанных с инъекцией заголовков. |
Примеры
Пример #1 Диалог загрузки
Если нужно предупредить пользователя о необходимости сохранить пересылаемые данные, такие как сгенерированный PDF файл, можно воспользоваться заголовком » Content-Disposition, который подставляет рекомендуемое имя файла и заставляет броузер показать диалог загрузки.
// Будем передавать PDF
header ( ‘Content-Type: application/pdf’ );
?php
// Который будет называться downloaded.pdf
header ( ‘Content-Disposition: attachment; filename=»downloaded.pdf»‘ );
// Исходный PDF файл original.pdf
readfile ( ‘original.pdf’ );
?>
Пример #2 Директивы для работы с кэшем
PHP скрипты часто генерируют динамический контент, который не должен кэшироваться клиентским броузером или какими-либо промежуточными обработчиками, вроде прокси серверов. Можно принудительно отключить кэширование на многих прокси серверах и броузерах, передав заголовки:
header ( «Cache-Control: no-cache, must-revalidate» ); // HTTP/1.1
header ( «Expires: Sat, 26 Jul 1997 05:00:00 GMT» ); // Дата в прошлом
?>?php
Замечание:
В некоторых случаях ваши страницы не будут кэшироваться броузером, даже если вы не передавали этих заголовков. В броузерах есть определенные настройки, с помощью которых пользователь может изменять обычный ход кэширования, отключать его. Вы должны перекрывать любые настройки, которые могут повлиять на кэширование скрипта, отправляя приведенные выше заголовки.
Дополнительно, для случаев когда используются сессии, можно задать настройки конфигурации session_cache_limiter() и session.cache_limiter. Эти настройки можно использовать для автоматической генерации заголовков управляющих кешированием.
Примечания
Замечание:
Доступ к заголовкам и их вывод будет осуществляться только в случае, если в используемом вами SAPI есть их поддержка.
Замечание:
Чтобы обойти эту проблему, можно буферизовать вывод скрипта. В этом случае все выводимые данные будут буферизоваться на сервере, пока не будет дана явная команда на пересылку данных. Управлять буферизацией можно вручную функциями ob_start() и ob_end_flush() , либо задав директиву output_buffering в конфигурационном файле php.ini , или же настроив соответствующим образом конфигурацию сервера.
Замечание:
Строка заголовка задающая состояние HTTP всегда будет отсылаться клиенту первой, вне зависимости от того был соответствующий вызов функции header() первым или нет. Это состояние можно перезаписать, вызывая header() с новой строкой состояния в любое время, когда можно отправлять HTTP заголовки.
Замечание:
В Microsoft Internet Explorer 4.01 есть баг, из-за которого это не работает. Обойти его никак нельзя. В Microsoft Internet Explorer 5.5 также есть этот баг, но его уже можно устранить установкой Service Pack 2 или выше.
Замечание: Если включен безопасный режим, то uid скрипта будет добавляться к realm части WWW-Authenticate заголовка (используется для HTTP аутентификации).
Замечание:
Спецификация HTTP/1.1 требует указывать абсолютный URI в качестве аргумента » Location:, включающий схему, имя хоста и абсолютный путь, хотя некоторые клиенты способны принимать и относительные URI. Абсолютный URI можно построить самостоятельно с помощью $_SERVER[‘HTTP_HOST’] , $_SERVER[‘PHP_SELF’] и dirname() :
/* Перенаправление броузера на другую страницу в той же директории, что и
изначально запрошенная */
$host = $_SERVER [ ‘HTTP_HOST’ ];
$uri = rtrim ( dirname ( $_SERVER [ ‘PHP_SELF’ ]), ‘/\\’ );
$extra = ‘mypage.php’ ;
header ( «Location: http:// $host$uri / $extra » );
exit;
?>?php
Замечание:
ID сессии не будет передаваться вместе с заголовком Location, даже если включена настройка session.use_trans_sid. Его нужно передавать вручную, используя константу SID .
Смотрите также
- headers_sent() — Проверяет были ли и куда отправлены заголовки
- setcookie() — Посылает cookie
- http_response_code() — Получает или устанавливает код ответа HTTP
- Раздел документации HTTP аутентификация
The Header Location in PHP
- Introduction to the Header() Function and Its Syntax in PHP
- Use the header() Function With the location: Header String in PHP
This article will introduce the concept of the header() function and its syntax in PHP. It will cover the rules of writing header in PHP. This method will also work with the Content-Type and Content-Disposition header.
We will also introduce the location: header string in this article. We will explain the usage and essence of the location header in PHP. The article will demonstrate how the header location sends the response code and redirects the browser to another page.
Introduction to the Header() Function and Its Syntax in PHP
The header() function is an in-built PHP function that lets us send a raw HTTP header to the client. The header sent is in the raw form. We should invoke the header() function before any output is sent. The output in any form, like the output sent by the HTML tags or a PHP form, should be discarded before sending the header information. Thus we can control the information sent to the browser by the server before any output.
The syntax of the header() function is: header(string,replace,http_response_code); . The function accepts three parameters. The first argument is a header string. There are two types of header strings. The first type is a string that starts with HTTP/ . It specifies the HTTP codes to be sent to the browser. The second type of the header string is the location: header, which redirects the browser to the specified location. The next parameter in the function is replace , which represents a boolean value. It is an optional parameter that determines if the header should replace the previous similar header. The third parameter, http_response code is also an optional parameter that forces the HTTP response code to the specified value.
For example, create a header() function and use the header string as Content-Type . Write the value of the Content-Type as application/pdf . Again create another header() function. This time, write the header string as Content-Disposition . Give the value of the string as attachment . Do not forget a semicolon after it. Write another attribute filename after the semicolon and provide the filename as download.pdf .
When we run the following script, then a download dialog box appears. It asks you to download a pdf file named download.pdf . The first header indicates the file should be of pdf format, and the second header denotes the filename of the file and forces the browser to display the dialog to save the file.
#php 7.x php header('Content-Type: application/pdf'); header('Content-Disposition: attachment; filename="downloaded.pdf"'); ?>
Use the header() Function With the location: Header String in PHP
We can use the header() function with the location: header string in PHP. The header string redirects the webpage to the location specified. It is generally used in web pages to redirect the user to a specific page after submitting the input. For instance, when the user inputs the correct credentials while logging in, we can use the header location to redirect them to the homepage. We can specify the boolean value and the response code in the header() function. However, these parameters are optional. The default boolean value is true that means that it will replace the previous similar header. We can also provide the response code as the third parameter. The default response code is 302 . For example, we can write an array to a file and redirect the current page to another page displaying the message that the file has been written. We can use the file_put_contents() function to write into the file.
For example, create an array on the $day variable. Create the keys as weather and time and the respective values as Sunny and 1:30 pm . Then use the file_input_contents() and specify a file file.txt as the first parameter. Use the print_r() function as the second parameter. Supply the variable $day and boolean value true as the parameters of the print_r() function. Evaluate the whole expression using the if condition. Inside the if block use the header() function. Specify the location as message.php inside the function. Use the colon : to specify the location. Note that there should not be any gap between the location and the : colon. Create a PHP file message.php . Display a message in the file saying that the file has been written.
In the example above, the array is written to the file file.txt . The if condition evaluates true and the header() function redirects the location to message.php . Thus, the output is shown. We can also see the changed URL in the address bar. If there had been another header function below the existing header function, the latter one would replace the former header. This is because the default value of the replace option is true in the header() function.
#php 7.x php $day = array ( 'weather' => 'Sunny', 'time' => '1:30 pm', ); if(file_put_contents('file.txt', print_r($day, true))) header("location: message.php"); > ?>
The file has been written.