header php что такое

Header php что такое

Описание

int header (string string [, bool replace])

header() используется для отправки необработанных HTTP-шапок. См. в спецификации HTTP/1.1 информацию о HTTP headers.

Необязательный параметр replace указывает, должна ли шапка замещать предыдущую аналогичную шапку, или нужно добавить вторую header того же самого типа. По умолчанию выполняется замещение, но, если вы передаёте FALSE в качестве второго аргумента, вы можете форсировать создание нескольких headers одного типа. Например:

Здесь два особых вызова шапок.В первом это header, начинающийся строкой » HTTP/ » (регистр не имеет значения), используемый для создания HTTP статус-кода для отправки. Например, если вы сконфигурировали Apache для использования PHP-скрипта для обработки запросов отсутствующих файлов (используя директиву ErrorDocument ), вам потребуется удостовериться, что ваш скрипт генерирует соответствующий статус-код.

Примечание: строка шапки HTTP-статуса всегда будет отправляться первой клиенту, независимо от того, идёт вызов header() первым или нет. Этот статус может быть переопределён вызовом header() с новой строкой статуса в любое время, если только HTTP headers уже не отправлены.

Второй особый случай это «Location:» header.Здесь header не только отсылается обратно браузеру, но также возвращается статус-код REDIRECT (302), если только какой-нибудь 3xx статус-код не был уже установлен.

PHP-скрипты часто генерируют динамическое содержимое, которое обязано не кэшироваться клиентским браузером или proxy-кэшами между клиентским браузером и сервером. Во многих прокси и клиентах можно отключать кэширование

Примечание: вы можете обнаружить, что ваши страницы не кэшируются, даже если вы не выводите все выше указанные шапки. Есть опции, которые могут быть установлены пользователями в своих браузерах, изменяющие поведение по умолчанию кэширования. Отправляя вышеуказанные шапки, вы должны переопределить любые установки, которые иначе могут кэшировать ваши скрипты.

Кроме того, session_cache_limiter() и установка конфигурации session.cache_limiter могут использоваться для автоматической генерации корректны шапок кэширования, когда используются сессии.

Примечание: в PHP 4 вы можете использовать буферизацию вывода для решения этой проблемы, передавая браузеру весь ваш вывод, буферизуемый на сервере до отправки. Вы можете сделать это вызовом ob_start() и ob_end_flush() в вашем скрипте, или установив директиву конфигурации output_buffering в файле php.ini или файлах конфигурации сервера.

Если вы хотите, чтобы пользователю задавался вопрос о сохранении данных, высылаемых вами, таких как сгенерированный PDF-файл, вы можете использовать шапку Content-Disposition для предоставления рекомендуемого файла и форсировать отображение браузером диалога save.

Примечание: в Microsoft Internet Explorer 4.01 имеется жучок, не дающий реализовать это. Средства от этого нет. Также имеется жучок в Microsoft Internet Explorer 5.5, но его можно исправить, обновив до Service Pack 2 или новее.

Источник

header — Отправка HTTP заголовка

Описание

header() используется для отправки HTTP заголовка. В » спецификации HTTP/1.1 есть подробное описание HTTP заголовков.

Список параметров

Существует два специальных заголовка. Один из них начинается с «HTTP/» (регистр не важен) и используется для отправки кода состояния HTTP. Например, если веб-сервер Apache сконфигурирован таким образом, чтобы запросы к несуществующим файлам обрабатывались средствами PHP скрипта (используя директиву ErrorDocument), вы наверняка захотите быть уверенными что скрипт генерирует правильный код состояния.

Другим специальным видом заголовков является «Location:». В этом случае функция не только отправляет этот заголовок броузеру, но также возвращает ему код состояния REDIRECT (302) (если ранее не был установлен код 201 или 3xx).

( «Location: http://www.example.com/» ); /* Перенаправление броузера */

/* Можно убедиться, что следующий за командой код не выполнится из-за
перенаправления.*/
exit;
?>

Принудительно задает код ответа HTTP. Следует учитывать, что это будет работать, только если строка string не является пустой.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Список изменений

ВерсияОписание
5.1.2Стало невозможно отправлять более одного заголовка за раз. Это сделано для защиты от атак, связанных с инъекцией заголовков.

Примеры

Пример #1 Диалог загрузки

Если нужно предупредить пользователя о необходимости сохранить пересылаемые данные, такие как сгенерированный PDF файл, можно воспользоваться заголовком » Content-Disposition, который подставляет рекомендуемое имя файла и заставляет броузер показать диалог загрузки.

// Будем передавать PDF
header ( ‘Content-Type: application/pdf’ );

// Который будет называться downloaded.pdf
header ( ‘Content-Disposition: attachment; filename=»downloaded.pdf»‘ );

// Исходный PDF файл original.pdf
readfile ( ‘original.pdf’ );
?>

Пример #2 Директивы для работы с кэшем

PHP скрипты часто генерируют динамический контент, который не должен кэшироваться клиентским броузером или какими-либо промежуточными обработчиками, вроде прокси серверов. Можно принудительно отключить кэширование на многих прокси серверах и броузерах, передав заголовки:

В некоторых случаях ваши страницы не будут кэшироваться броузером, даже если вы не передавали этих заголовков. В броузерах есть определенные настройки, с помощью которых пользователь может изменять обычный ход кэширования, отключать его. Вы должны перекрывать любые настройки, которые могут повлиять на кэширование скрипта, отправляя приведенные выше заголовки.

Дополнительно, для случаев когда используются сессии, можно задать настройки конфигурации session_cache_limiter() и session.cache_limiter. Эти настройки можно использовать для автоматической генерации заголовков управляющих кешированием.

Примечания

Доступ к заголовкам и их вывод будет осуществляться только в случае, если в используемом вами SAPI есть их поддержка.

Строка заголовка задающая состояние HTTP всегда будет отсылаться клиенту первой, вне зависимости от того был соответствующий вызов функции header() первым или нет. Это состояние можно перезаписать, вызывая header() с новой строкой состояния в любое время, когда можно отправлять HTTP заголовки.

В Microsoft Internet Explorer 4.01 есть баг, из-за которого это не работает. Обойти его никак нельзя. В Microsoft Internet Explorer 5.5 также есть этот баг, но его уже можно устранить установкой Service Pack 2 или выше.

Замечание: Если включен безопасный режим, то uid скрипта будет добавляться к realm части WWW-Authenticate заголовка (используется для HTTP аутентификации).

Смотрите также

Источник

header

(PHP 4, PHP 5, PHP 7, PHP 8)

header — Отправка HTTP-заголовка

Описание

Список параметров

Существует два специальных заголовка. Один из них начинается с » HTTP/ » (регистр не важен) и используется для отправки кода состояния HTTP. Например, если веб-сервер Apache сконфигурирован таким образом, чтобы запросы к несуществующим файлам обрабатывались средствами PHP-скрипта (используя директиву ErrorDocument ), вы наверняка захотите убедиться, что скрипт генерирует правильный код состояния.

( «Location: http://www.example.com/» ); /* Перенаправление браузера */

Принудительно задаёт код ответа HTTP. Следует учитывать, что это будет работать, только если строка header не является пустой.

Возвращаемые значения

Функция не возвращает значения после выполнения.

Ошибки

Примеры

Пример #1 Диалог загрузки

Если нужно предупредить пользователя о необходимости сохранить пересылаемые данные, такие как сгенерированный PDF-файл, можно воспользоваться заголовком » Content-Disposition, который подставляет рекомендуемое имя файла и заставляет браузер показать диалог загрузки.

// Будем передавать PDF
header ( ‘Content-Type: application/pdf’ );

// Он будет называться downloaded.pdf
header ( ‘Content-Disposition: attachment; filename=»downloaded.pdf»‘ );

// Исходный PDF-файл original.pdf
readfile ( ‘original.pdf’ );
?>

Пример #2 Директивы для работы с кешем

PHP-скрипты часто генерируют динамический контент, который не должен кешироваться клиентским браузером или какими-либо промежуточными обработчиками, вроде прокси-серверов. Можно принудительно отключить кеширование на многих прокси-серверах и браузерах, передав заголовки:

В некоторых случаях ваши страницы не будут кешироваться браузером, даже если вы не передавали этих заголовков. В браузерах есть определённые настройки, с помощью которых пользователь может изменять обычный ход кеширования, отключать его. Вы должны переопределять любые настройки, которые могут повлиять на кеширование скрипта, отправляя приведённые выше заголовки.

Примечания

Доступ к заголовкам и их вывод будет осуществляться только в случае, если в используемом вами SAPI есть их поддержка.

Строка заголовка состояния HTTP всегда будет отсылаться клиенту первой, вне зависимости от того был соответствующий вызов функции header() первым или нет. Это состояние можно перезаписать, вызывая header() с новой строкой состояния в любое время, когда можно отправлять HTTP-заголовки.

Смотрите также

User Contributed Notes 40 notes

I strongly recommend, that you use

header($_SERVER[«SERVER_PROTOCOL»].» 404 Not Found»);

header(«HTTP/1.1 404 Not Found»);

Most of the pages were displayed correct, but on some of them apache added weird content to it:

A 4-digits HexCode on top of the page (before any output of my php script), seems to be some kind of checksum, because it changes from page to page and browser to browser. (same code for same page and browser)

«0» at the bottom of the page (after the complete output of my php script)

It took me quite a while to find out about the wrong protocol in the HTTP-header.

So, either you have to use the HTML meta refresh thingy or you use the following:

( «refresh:5;url=wherever.php» );
echo ‘You\’ll be redirected in about 5 secs. If not, click here.’ ;
?>

Hth someone

When using PHP to output an image, it won’t be cached by the client so if you don’t want them to download the image each time they reload the page, you will need to emulate part of the HTTP protocol.

// Test image.
$fn = ‘/test/foo.png’ ;

// Getting headers sent by the client.
$headers = apache_request_headers ();

?>

That way foo.png will be properly cached by the client and you’ll save bandwith. 🙂

If using the ‘header’ function for the downloading of files, especially if you’re passing the filename as a variable, remember to surround the filename with double quotes, otherwise you’ll have problems in Firefox as soon as there’s a space in the filename.

So instead of typing:

See the page called «Filenames_with_spaces_are_truncated_upon_download» at
http://kb.mozillazine.org/ for more information. (Sorry, the site won’t let me post such a long link. )

It seems the note saying the URI must be absolute is obsolete. Found on https://en.wikipedia.org/wiki/HTTP_location

«An obsolete version of the HTTP 1.1 specifications (IETF RFC 2616) required a complete absolute URI for redirection.[2] The IETF HTTP working group found that the most popular web browsers tolerate the passing of a relative URL[3] and, consequently, the updated HTTP 1.1 specifications (IETF RFC 7231) relaxed the original constraint, allowing the use of relative URLs in Location headers.»

According to the RFC 6226 (https://tools.ietf.org/html/rfc6266), the only way to send Content-Disposition Header with encoding is:

Content-Disposition: attachment;
filename*= UTF-8»%e2%82%ac%20rates

for backward compatibility, what should be sent is:

Content-Disposition: attachment;
filename=»EURO rates»;
filename*=utf-8»%e2%82%ac%20rates

As a result, we should use

= ‘中文文件名.exe’ ; // a filename in Chinese characters

header ( ‘Content-Type: application/octet-stream’ );

readfile ( ‘file_to_download.exe’ );
?>

I have tested the code in IE6-10, firefox and Chrome.

Be aware that sending binary files to the user-agent (browser) over an encrypted connection (SSL/TLS) will fail in IE (Internet Explorer) versions 5, 6, 7, and 8 if any of the following headers is included:

Workaround: do not send those headers.

Also, be aware that IE versions 5, 6, 7, and 8 double-compress already-compressed files and do not reverse the process correctly, so ZIP files and similar are corrupted on download.

Workaround: disable compression (beyond text/html) for these particular versions of IE, e.g., using Apache’s «BrowserMatch» directive. The following example disables compression in all versions of IE:

BrowserMatch «.*MSIE.*» gzip-only-text/html

It is important to note that headers are actually sent when the first byte is output to the browser. If you are replacing headers in your scripts, this means that the placement of echo/print statements and output buffers may actually impact which headers are sent. In the case of redirects, if you forget to terminate your script after sending the header, adding a buffer or sending a character may change which page your users are sent to.

This redirects to 2.html since the second header replaces the first.

( «location: 1.html» );
header ( «location: 2.html» ); //replaces 1.html
?>

This redirects to 1.html since the header is sent as soon as the echo happens. You also won’t see any «headers already sent» errors because the browser follows the redirect before it can display the error.

( «location: 1.html» );
echo «send data» ;
header ( «location: 2.html» ); //1.html already sent
?>

Wrapping the previous example in an output buffer actually changes the behavior of the script! This is because headers aren’t sent until the output buffer is flushed.

();
header ( «location: 1.html» );
echo «send data» ;
header ( «location: 2.html» ); //replaces 1.html
ob_end_flush (); //now the headers are sent
?>

$code = 301 ;
// Use when the old page has been «permanently moved and any future requests should be sent to the target page instead. PageRank may be transferred.»

$code = 302 ; (default)
// «Temporary redirect so page is only cached if indicated by a Cache-Control or Expires header field.»

$code = 303 ;
// «This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource and is not cached.»

$code = 307 ;
// Beware that when used after a form is submitted using POST, it would carry over the posted values to the next page, such if target.php contains a form processing script, it will process the submitted info again!

// In other words, use 301 if permanent, 302 if temporary, and 303 if a results page from a submitted form.
// Maybe use 307 if a form processing script has moved.

You can use HTTP’s etags and last modified dates to ensure that you’re not sending the browser data it already has cached.

Just to inform you all, do not get confused between Content-Transfer-Encoding and Content-Encoding

Content-Transfer-Encoding specifies the encoding used to transfer the data within the HTTP protocol, like raw binary or base64. (binary is more compact than base64. base64 having 33% overhead).
Eg Use:- header(‘Content-Transfer-Encoding: binary’);

Content-Encoding is used to apply things like gzip compression to the content/data.
Eg Use:- header(‘Content-Encoding: gzip’);

/* This will give an error. Note the output
* above, which is before the header() call */
header ( ‘Location: http://www.example.com/’ );
exit;
?>

this example is pretty good BUT in time you use «exit» the parser will still work to decide what’s happening next the «exit» ‘s action should do (’cause if you check the manual exit works in others situations too).
SO MY POINT IS : you should use :
( ‘Location: http://www.example.com/’ );
die();

there are many situations with others examples and the right choose for small parts of your scrips that make differences when you write your php framework at well!

Please note that there is no error checking for the header command, either in PHP, browsers, or Web Developer Tools.

If you use something like «header(‘text/javascript’);» to set the MIME type for PHP response text (such as for echoed or Included data), you will get an undiagnosed failure.

The proper MIME-setting function is «header(‘Content-type: text/javascript’);».

Note that ‘session_start’ may overwrite your custom cache headers.
To remedy this you need to call:

. after you set your custom cache headers. It will tell the PHP session code to not do any cache header changes of its own.

For large files (100+ MBs), I found that it is essential to flush the file content ASAP, otherwise the download dialog doesn’t show until a long time or never.

After lots of research and testing, I’d like to share my findings about my problems with Internet Explorer and file downloads.

Take a look at this code, which replicates the normal download of a Javascript:

I start out by checking for IE, then if not IE, I set Content-type (case-sensitive) to JS and set Content-Disposition (every header is case-sensitive from now on) to inline, because most browsers outside of IE like to display JS inline. (User may change settings). The Content-Length header is required by some browsers to activate download box. Then, if it is IE, the «application/force-download» Content-type is sometimes required to show the download box. Use this if you don’t want your PDF to display in the browser (in IE). I use it here to make sure the box opens. Anyway, I set the Content-Disposition to attachment because I already know that the box will appear. Then I have the Content-Length again.

Now, here’s my big point. I have the Cache-Control and Pragma headers sent only if not IE. THESE HEADERS WILL PREVENT DOWNLOAD ON IE. Only use the Expires header, after all, it will require the file to be downloaded again the next time. This is not a bug! IE stores downloads in the Temporary Internet Files folder until the download is complete. I know this because once I downloaded a huge file to My Documents, but the Download Dialog box put it in the Temp folder and moved it at the end. Just think about it. If IE requires the file to be downloaded to the Temp folder, setting the Cache-Control and Pragma headers will cause an error!

I hope this saves someone some time!

I just want to add, becuase I see here lots of wrong formated headers.

1. All used headers have first letters uppercase, so you MUST follow this. For example:

Location, not location
Content-Type, not content-type, nor CONTENT-TYPE

2. Then there MUST be colon and space, like

good: header(«Content-Type: text/plain»);
wrong: header(«Content-Type:text/plain»);

3. Location header MUST be absolute uri with scheme, domain, port, path, etc.

4. Relative URIs are NOT allowed

It will make proxy server and http clients happier.

If you want to remove a header and keep it from being sent as part of the header response, just provide nothing as the header value after the header name. For example.

PHP, by default, always returns the following header:

Which your entire header response will look like

HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Content-Type: text/html; charset=UTF-8
Connection: close

If you call the header name with no value like so.

?>

Your headers now look like this:

HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Connection: close

If you haven’t used, HTTP Response 204 can be very convenient. 204 tells the server to immediately termiante this request. This is helpful if you want a javascript (or similar) client-side function to execute a server-side function without refreshing or changing the current webpage. Great for updating database, setting global variables, etc.

header(«status: 204»); (or the other call)
header(«HTTP/1.0 204 No Response»);

I made a script that generates an optimized image for use on web pages using a 404 script to resize and reduce original images, but on some servers it was generating the image but then not using it due to some kind of cache somewhere of the 404 status. I managed to get it to work with the following and although I don’t quite understand it, I hope my posting here does help others with similar issues:

My files are in a compressed state (bz2). When the user clicks the link, I want them to get the uncompressed version of the file.

After decompressing the file, I ran into the problem, that the download dialog would always pop up, even when I told the dialog to ‘Always perform this operation with this file type’.

As I found out, the problem was in the header directive ‘Content-Disposition’, namely the ‘attachment’ directive.

If you want your browser to simulate a plain link to a file, either change ‘attachment’ to ‘inline’ or omit it alltogether and you’ll be fine.

This took me a while to figure out and I hope it will help someone else out there, who runs into the same problem.

A call to session_write_close() before the statement

( «Location: URL» );
exit();
?>

is recommended if you want to be sure the session is updated before proceeding to the redirection.

We encountered a situation where the script accessed by the redirection wasn’t loading the session correctly because the precedent script hadn’t the time to update it (we used a database handler).

(But the strange behaviour of dirname is a problem for URL ending by a directory without file name!)

The piece of code in the manual which is as follows

This is the Headers to force a browser to use fresh content (no caching) in HTTP/1.0 and HTTP/1.1:

Here is a php script I wrote to stream a file and crypt it with a xor operation on the bytes and with a key :

The encryption works very good but the speed is decrease by 2, it is now 520KiB/s. The user is now asked for a md5 password (instead of keeping it in the code directly). There is some part in French because it’s my native language so modify it as you want.

// Stream files and encrypt the data on-the-fly

Источник

Header.php — Что нужно для этого, а что нет

Шаг 1: Введение

Первое, что вам нужно знать о файле header.php, это ваша функция.

Помните, что ваш заголовок — это весь контент, который отображается на всех страницах вашего сайта. Например, логотип и меню отображаются на всех страницах, поэтому … оба будут добавлены в header.php

Если элемент отображается только на определенной странице, вам нужно подумать, действительно ли этот элемент должен находиться внутри вашего заголовка.

Давайте работать, и я надеюсь, что вам это нравится!

Шаг 2: Окончательный код

Здесь вы можете получить окончательный код для использования в вашей теме. Прочитайте другие шаги, чтобы точно знать, что делает каждая строка.

Сначала вставьте эти строки вверху вашего файла functions.php : (Помните, что вам нужно изменить пути к вашим файлам CSS и JavaScript)

Теперь внутри вашего header.php добавьте эти строки: (Помните, что вам нужно изменить пути к вашим файлам CSS и JavaScript)

Заголовок «должен» иметь некоторые вещи, этот шаблон, который я сделал, делает следующее (на следующих шагах я расскажу о каждом):

Шаги ниже расскажут об используемом коде и вы узнаете, почему его использовать.

Шаг 2: Файл functions.php

Эта строка удаляет мета-тег генератора, потому что этот тег показывает всем, кто установил версию WordPress. Такая информация может позволить злоумышленнику узнать ошибки вашей версии и использовать их.

Добавление вашего CSS

Внутри нашей функции у нас есть следующие строки:

Сначала мы регистрируем нашу таблицу стилей, а затем добавляем ее в очередь WordPress.

Мы используем функцию wp_register_style для регистрации стиля, эта функция запрашивает следующее:

Затем мы вызываем функцию wp_enqueue_style и передаем в качестве параметра имя нашего стиля, который будет добавлен.

Чтобы добавить больше стилей в ваш файл, просто продублируйте эти две строки и измените имя, каталог и другие параметры.

Добавление сценариев

Теперь мы увидим функцию, которая добавляет наши скрипты.

Здесь процесс такой же, разница здесь в том, что мы используем другие функции для добавления скриптов.

Затем мы вызываем функцию wp_enqueue_script и передаем в качестве параметра имя нашего скрипта, который будет добавлен.

Чтобы добавить больше скриптов в ваш файл, просто продублируйте эти две строки и измените имена, каталог и другие параметры.

Шаг 3: header.php

Сначала я перечислю здесь ссылки на библиотеки, которые вы можете использовать в этом шаблоне, я уже использую jQuery и HTML5 Shim в этом шаблоне, но вы можете добавить другие.

Doctype

В этом шаблоне мы просто используем тип документа HTML5 по умолчанию:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *