Using header in php

PHP Header header() function in PHP?

Original and detailed post of this tutorial is located at What is header() function in PHP? As per php.net documentation, the header function is mainly used to send a raw HTTP header. Well, in the beginning, it is confusing to know the term raw HTTP. In this tutorial, we’ll see what is header() function in PHP, its importance, and its uses.

Use of header() function in PHP

header() function in PHP is used to send raw HTTP header and it must be called before any output is sent to the requester, either by normal HTML tags, blank lines in a file, or from PHP. The main purpose of header() function is to redirect user from the current/certain page to another URL. Let’s understand the syntax first and then we’ll see individual parameters.

Where, $header: is the header string which has two special-case header calls. One is the “Location:” and another is the “HTTP/“.
$replace: Optional. It indicates whether the header should replace a previously sent similar header, or add another header of the same type.
$http_response_code: It forces the HTTP response code to the specified value.

Читайте также:  Функция лапласа в питоне

Using “Location:”

With “HTTP/” parameter can contain any HTTP status code to send. For example, if we have configured Apache to use a PHP script to handle requests for missing files then we can redirect user to the specified file

 header("HTTP/1.0 404 Not Found"); 

This will show a 404 page not found page because we have added security restriction for accessing certain pages so that if the user tries to access those page then we’ll certainly show not found page.

Download file using header in PHP

The advantage of header function is that we can create and download files on the fly. This is a very important feature that is needed while working with files related operations in the project.

 // what kind of document to be downloaded header('Content-Type: application/pdf'); // name the file as document.pdf header('Content-Disposition: attachment; filename="document.pdf"'); // Read original.pdf file and output it readfile('original.pdf'); 
  • Define type of file to be downloaded
  • name that file
  • read the content of the file/text

Besides other intermediate steps, these are the 3 basic steps which are used to download file on the fly.

Set HTTP headers to prevent page caching

PHP is quite famous for its dynamic data. But there are certain situations where we don’t client browser to cached those data (to load website faster of course )

We can use header() function to override such a situation and add certain parameters that will prevent webpages from being cached.

 header("expires: Wed, 11 Jan 1984 05:00:00 GMT"); header("cache-control: no-cache, must-revalidate, max-age=0"); ?> 

Here, we have added cache-control: no-cache to make sure that each time browser request for a particular webpage then server must send updated data rather than cached one.

We’ve also added expires parameter to past date represents that web-page is already expired and new data is expected from the client browser.

Conclusion:

Introduced in PHP 4, header function plays an important role while development. May modern frameworks used this function in the core to redirect users to a specific function. Downloading file at runtime, setting cache-control is the of the main features in header() function

I hope that I have covered all the related information about what is header() function in PHP and it’s related uses. If you have any questions Or you think any need for improvement then please comment.

Источник

Функция header

HTTP заголовки это специальная информация, которая присоединяется к документу, то есть, к тому файлу, который запрашивается браузером с сервера. Когда мы вбиваем в адресную строку какой-нибудь адрес то, соответственно, запрашиваем на сервере по этому адресу какой-нибудь документ. Эта информация(документ) видна у нас на экране. Но кроме видимой части есть еще и невидимая — те самые HTTP заголовки, которые отправляются сервером браузеру и они нужны для того, чтобы браузер корректно отобразил страницу. То есть, заголовки подсказывают браузеру как показать страницу или как отдать страницу.

Для браузера firefox: кнопка F12 -> сеть -> кликнуть «статус» и обновить страницу :

header1

Среди прочего в заголовках отправляется информация о кодировке страницы, как давно модифицировалась страница, информация о том, что это за страница (html-страница, обычный текстовый документ; или, вместо того чтобы показать страницу, отдать ее на скачивание)

Установление кодировки

Один, из наиболее часто используемых вариантов функции header , это использование функции для установления кодировки.

В файле index.php в папке с нашим уроком запишем: привет, мир! и посмотрим в браузере, что получили. Мы можем получить крабозябры . Это происходит по тому, что браузер будет открывать документ в той кодировке, которую сервер отправил в заголовках по умолчанию. Если кодировка нашего документа не совпадает с кодировкой сервера — получим крабозябры.

Кодировка для всех частей нашего приложения должна быть единой .

Рекомендуется всегда использовать кодировку utf-8 — как универсальную кодировку.

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

В этом случае мы должны переопределить кодировку сервера с помощью функции header . (php.net)

Функция header позволяет указать нужную нам кодировку.

header ( ‘Content-Type: text/html; charset=utf-8’ );
?>

где:
text/html — тип документа;
charset=utf-8 — нужная нам кодировка.

Если посмотрим заголовки в «разработка/инструменты разработчика/сеть» (в firefox ), то увидим, что они дополнились кодировкой charset=»UTF-8″ , то есть, мы указали браузеру (отправили заголовки), что нужно использовать именно данную кодировку. При этом она имеет приоритет над метатэгом charset .

header2

Еще один способ установления кодировки по умолчанию — это использовать специальный файл .htaccess . Данный файл является файлом настройки сервера Apache .

Создадим даннный файл в нашей папке.

Установим кодировку для сервера по умолчанию с помощью специальной директивы AddDefaultCharset .

Данная директива заставляет сервер отправлять в заголовках кодировку, указанную в качестве значения данной дериктивы.

Организация редиректа

Функцию header часто используют для редиректа .

Создадим новый файл — inc.php и выведем в нем строку: «привет из подключаемого файла» .

echo ‘Привет из подключаемого файла’ ;
?>

В индексном файле используем функцию header для редиректа. Его можно сделать двумя командами:
— командой ‘ Location ‘
— командой ‘ refresh ‘

header ( ‘Content-Type: text/html; charset=utf-8’ );
header ( ‘Location: inc.php’ ); // где inc.php — относительный путь к файлу
?>

При работе с редиректом нужно помнить что редирект происходит не сразу. Когда отрабатывает
данная команда ( header(‘Location: inc.php’); ), выполнение файла продолжается дальше.
Чтобы сделать безусловный редирект и не выполнять дальнейший код нужно воспользоватся
одной из двух команд — функция die (пер.- умри) и функция exit (пер.- выйти).
Эти команды почти всегда рекомендуется использовать после редиректа.

Чтобы убедиться, что у нас код после команды редиректа выполняется, используем редирект
с задержкой: header(‘refresh: 5, url’) , где
5 — время задержки в секундах,
url=inc.php — адрес, на который должен быть перенаправлен пользователь (если внешний адрес,
то используем — http, если внутренний, то используем — относительный путь к файлу ).
Запускаем файл index.php:

header ( ‘Content-Type: text/html; charset=utf-8’ );

header( ‘Location: inc.php’ );
// — где inc.php — относительный путь к файлу

header ( ‘refresh: 5, url=inc.php’ );
// — адрес, на который должен быть перенаправлен пользователь

— после загрузки документа весь код у нас выполнился — выводится: привет мир!
После пятисекундной задержки нас перенаправляет на другой файл ( inc.php ) — выводится: привет из подключаемого файла .
Чтобы код не выполнялся используем любую из функций: либо exit , либо die .

header ( ‘Content-Type: text/html; charset=utf-8’ );
header( ‘Location: inc.php’ );
// — где inc.php — относительный путь к файлу

header ( ‘refresh: 5, url=inc.php’ );
exit ;
// die;
?>

— после загрузки документа код у нас не выполняется — видим пустую страницу.
После пятисекундной задержки перенаправляемся на другой файл — выводится: привет из подключаемого файла .

Проблемы вывода

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

1. В этом легко убедиться, если в индексном файле поставим какой нибудь вывод, например, перенос строки перед функцией header :

— не удается изменить информацию заголовка — заголовки уже отправленны .

Выводом считается любой символ , который показывается в браузере, например, даже пробел.

2. С проблемой вывода можно столкнуться при подключении какого нибудь файла.

Например, мы подключаем файл inc.php, и в нем есть какая-то переменная — $test = ‘TEST’ .

В индексном файле мы хотим использовать данную переменную: $test ?> .

Источник

Header in PHP: The Ultimate Guide to Header Function

The Entire Concept of Header in PHP in Detail

PHP stands for Hypertext Preprocessor and is a server-side programming language that was created with web development in mind. It is open-source, which means you can download and use it for free. It’s incredibly easy to pick up and use. The files contain the “.php” extension.

Rasmus Lerdorf was the driving force behind the first version of PHP, as well as a contributor to succeeding versions. It is an interpreted language that does not necessitate the use of a compiler.

Many databases, including Oracle, Microsoft SQL Server, MySQL, PostgreSQL, Sybase, and Informix, can be combined with it.

It is used to regulate user access and hold a content management system like WordPress.

Example

Output

/Header_In_PHP_1

Stand Out From Your Peers this Appraisal Season

What Is a Header in PHP? Explain With Syntax

The header in PHP is a PHP built-in function for sending a raw HTTP header. The HTTP functions are those that manipulate information sent by the webserver to the client or browser before it sends any further output. The header() function in PHP sends a raw HTTP header to a client or browser. Before HTML, XML, JSON, or other output is given to a browser or client, the server sends raw data as header information with the request (particularly HTTP Request). Headers in PHP contain additional details about the object delivered in the message body, as well as the request and response.

Syntax

void header( $header, $replace = TRUE, $http_response_code )

It includes a header string in the string. There are two types of header calls in general. One is a header that begins with the string «HTTP/» and is used to determine the HTTP status code to send. Another is the «Location,» which is required.

  • replace: This is an optional parameter that specifies whether the header should add a new header or replace the previous one.
  • http response code is an optional parameter that sets the HTTP response code to a specific value (available in PHP 4.3 and higher).

The header() method is a built-in function that allows you to deliver a raw HTTP header to a client. HTTP functions allow you to manipulate data supplied to the browser by the webserver before it sends any additional output. You must call it before any actual output is sent, whether from HTML tags, blank lines in a file, or a PHP file.

Example

header(«Expires: Sun, 22 Jun 1997 04:00:00 GMT»);

header(«Cache-Control: no-cache, must-revalidate»);

Источник

Оцените статью