I strongly recommend, that you use
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
instead of
header("HTTP/1.1 404 Not Found");
I had big troubles with an Apache/2.0.59 (Unix) answering in HTTP/1.0 while I (accidentially) added a "HTTP/1.1 200 Ok" - Header.
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.header
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
header
Референца за `function.header.php` со подобрена типографија и навигација.
header
(PHP 4, PHP 5, PHP 7, PHP 8)
header — Испрати суров HTTP заглавие
= NULL
header() се користи за испраќање суров HTTP заглавие. Погледнете го » HTTP/1.1 спецификацијата за повеќе информации за HTTP headers.
Запомнете дека header() мора да се повика пред да се испрати каков било реален излез, или од нормални HTML ознаки, празни редови во датотека, или од PHP. Многу честа грешка е да се чита код со include, или require, функции, или друга функција за пристап до датотеки, и да има празни места или празни редови што се испраќаат пред header() да се повика. Истиот проблем постои кога се користи една PHP/HTML датотека.
<html>
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>Параметри
header-
Заглавието стринг.
Постојат два посебни случаи на повици за заглавие. Првиот е заглавие што започнува со стринг "
HTTP/" (случајот не е значаен), што ќе се користи за да се одреди HTTP статус кодот што треба да се испрати. На пример, ако сте конфигурирале Apache да користи PHP скрипта за ракување со барања за недостапни датотеки (користејќиErrorDocumentдирективата), можеби ќе сакате да се уверите дека вашата скрипта генерира соодветен статус код.<?php
// This example illustrates the "HTTP/" special case
// Better alternatives in typical use cases include:
// 1. header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
// (to override http status messages for clients that are still using HTTP/1.0)
// 2. http_response_code(404); (to use the default message)
header("HTTP/1.1 404 Not Found");
?>Вториот посебен случај е заглавието "Location:". Не само што го испраќа ова заглавие назад до прелистувачот, туку исто така враќа
REDIRECT(302) статус код до прелистувачот освен ако201или3xxстатус кодот веќе не е поставен.<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?> replace-
Опционалниот
replaceпараметар покажува дали заглавието треба да го замени претходното слично заглавие, или да додаде второ заглавие од истиот тип. Стандардно ќе го замени, но ако поминетеfalseкако втор аргумент можете да форсирате повеќе заглавија од ист тип. На пример:<?php
header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false);
?> response_code-
Ја форсира HTTP код за одговор на наведената вредност. Забележете дека овој параметар има ефект само ако
headerне е празно.
Вратени вредности
Не се враќа вредност.
Errors/Exceptions
При неуспех во закажувањето на испраќањето на заглавието, header()
издава E_WARNING Променето: Во претходните верзии на PHP 5, употребата на
Примери
Пример #1 Дијалог за преземање
Ако сакате корисникот да биде прашан да ги зачува податоците што ги испраќате, како што е генерирана PDF датотека, можете да го користите (PHP 4, PHP 5, PHP 7, PHP 8) заглавието за да обезбедите препорачано име на датотека и да го присилите прелистувачот да го прикаже дијалогот за зачувување.
<?php
// We'll be outputting a PDF
header('Content-Type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
?>
Пример #2 Директиви за кеширање
PHP скриптите често генерираат динамична содржина што не смее да се кешира од прелистувачот на клиентот или од кој било кеш на прокси помеѓу серверот и прелистувачот на клиентот. Многу прокси и клиенти може да бидат присилени да го оневозможат кеширањето со:
<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>
Забелешка:
Може да откриете дека вашите страници не се кешираат дури и ако не ги прикажувате сите заглавија погоре. Постојат голем број опции што корисниците можеби ќе можат да ги постават за нивниот прелистувач што го менуваат неговото стандардно однесување при кеширање. Со испраќање на заглавијата погоре, треба да ги надминете сите поставки што инаку може да предизвикаат прикажување на излезот од вашата скрипта да се кешира.
Дополнително, session_cache_limiter() Пример #4 Споредување на вратената вредност на include
session.cache_limiterпоставката за конфигурација може да се користи за автоматско генерирање на точните заглавија поврзани со кеширањето кога се користат сесии.
Пример #3 Поставување колаче
setcookie() обезбедува удобен начин за поставување колачиња. За да поставите колаче што вклучува атрибути кои setcookie() не поддржува, header() може да се користи.
На пример, следново поставува колаче што вклучува
Partitioned attribute.
<?php
header('Set-Cookie: name=value; Secure; Path=/; SameSite=None; Partitioned;');
?>Белешки
Забелешка:
Заглавијата ќе бидат достапни и прикажани само кога се користи SAPI што ги поддржува.
Забелешка:
Можете да користите баферирање на излезот за да го заобиколите овој проблем, со дополнителен трошок на целиот ваш излез до прелистувачот што се баферира на серверот додека не го испратите. Можете да го направите ова со повикување ob_start() and ob_end_flush() во вашата скрипта, или поставување на
output_bufferingдирективата за конфигурација вклучена во вашата php.ini директива за конфигурација на
Забелешка:
» Content-Disposition header() HTTP статусната линија на заглавието секогаш ќе биде прва испратена до клиентот, без оглед на тоа дали повикот е прв или не. Статусот може да биде поништен со повикување со нова статус линија во секое време, освен ако HTTP заглавијата веќе не се испратени. header() Повеќето современи клиенти прифаќаат релативни
Забелешка:
како аргумент за URI» Локација: , но некои постари клиенти бараат апсолутна URI вклучувајќи го шемата, името на домаќинот и апсолутната патека. Обично можете да користитеза да направите апсолутна URI од релативна сами: $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() ID на сесијата не се пренесува со заглавието Локација дури и ако
<?php
/* Redirect to a different page in the current directory that was requested */
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/$extra");
exit;
?>
Забелешка:
е овозможено. Мора да се пренесе рачно користејќи session.use_trans_sid - Проверува дали или каде се испратени заглавијата
SIDconstant.
Види Исто така
- headers_sent() - Земи или постави HTTP код за одговор
- setcookie() - Испрати колаче
- http_response_code() - Отстрани претходно поставени заглавија
- header_remove() - Враќа листа на заглавија за одговор испратени (или подготвени за испраќање)
- headers_list() Делот за
- HTTP автентикација mjt на jpeto dot net
Белешки од корисници 20 белешки
Several times this one is asked on the net but an answer could not be found in the docs on php.net ...
If you want to redirect an user and tell him he will be redirected, e. g. "You will be redirected in about 5 secs. If not, click here." you cannot use header( 'Location: ...' ) as you can't sent any output before the headers are sent.
So, either you have to use the HTML meta refresh thingy or you use the following:
<?php
header( "refresh:5;url=wherever.php" );
echo 'You\'ll be redirected in about 5 secs. If not, click <a href="wherever.php">here</a>.';
?>
Hth someoneA quick way to make redirects permanent or temporary is to make use of the $http_response_code parameter in header().
<?php
// 301 Moved Permanently
header("Location: /foo.php",TRUE,301);
// 302 Found
header("Location: /foo.php",TRUE,302);
header("Location: /foo.php");
// 303 See Other
header("Location: /foo.php",TRUE,303);
// 307 Temporary Redirect
header("Location: /foo.php",TRUE,307);
?>
The HTTP status code changes the way browsers and robots handle redirects, so if you are using header(Location:) it's a good idea to set the status code at the same time. Browsers typically re-request a 307 page every time, cache a 302 page for the session, and cache a 301 page for longer, or even indefinitely. Search engines typically transfer "page rank" to the new location for 301 redirects, but not for 302, 303 or 307. If the status code is not specified, header('Location:') defaults to 302.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.
Here's how:
<?php
// Test image.
$fn = '/test/foo.png';
// Getting headers sent by the client.
$headers = apache_request_headers();
// Checking if the client is validating his cache and if it is current.
if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == filemtime($fn))) {
// Client's cache IS current, so we just respond '304 Not Modified'.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 304);
} else {
// Image not cached or cache outdated, we respond '200 OK' and output the image.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 200);
header('Content-Length: '.filesize($fn));
header('Content-Type: image/png');
print file_get_contents($fn);
}
?>
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:
<?php
header("Content-Disposition: attachment; filename=" . basename($filename));
?>
you should type:
<?php
header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\"");
?>
If you don't do this then when the user clicks on the link for a file named "Example file with spaces.txt", then Firefox's Save As dialog box will give it the name "Example", and it will have no extension.
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...)If you use header() to allow the user to download a file, it's very important to check the encoding of the script itself. Your script should be encoded in UTF-8, but definitely not in UTF-8-BOM! The presence of BOM will alter the file received by the user. Let the following script:
<?php
$content = file_get_contents('test_download.png') ;
$name = 'test.png' ;
$size = strlen($content) ;
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Cache-Control: no-cache, must-revalidate');
header('Expires: 0');
header('Content-Disposition: attachment; filename="'.$name.'"');
header('Content-Length: ' . $size);
header('Pragma: public');
echo $content ;
?>
Irrespectively from the encoding of test_download.png, when this PHP script is encoded in UTF-8-BOM, the content received by the user is different:
- a ZWNBSP byte (U+FEFF) is added to the beginning of the file
- the file content is truncated!!!
If it's a binary file (e.g. image, proprietary format), the file will become unreadable.Since PHP 5.4, the function `http_response_code()` can be used to set the response code instead of using the `header()` function, which requires to also set the correct protocol version (which can lead to problems, as seen in other comments).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');".The header call can be misleading to novice php users.
when "header call" is stated, it refers the the top leftmost position of the file and not the "header()" function itself.
"<?php" opening tag must be placed before anything else, even whitespace.You can use HTTP's etags and last modified dates to ensure that you're not sending the browser data it already has cached.
<?php
$last_modified_time = filemtime($file);
$etag = md5_file($file);
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
header("Etag: $etag");
if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time ||
trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
header("HTTP/1.1 304 Not Modified");
exit;
}
?><?php
// Response codes behaviors when using
header('Location: /target.php', true, $code) to forward user to another page:
$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.
?>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
<?php
$filename = '中文文件名.exe'; // a filename in Chinese characters
$contentDispositionField = 'Content-Disposition: attachment; '
. sprintf('filename="%s"; ', rawurlencode($filename))
. sprintf("filename*=utf-8''%s", rawurlencode($filename));
header('Content-Type: application/octet-stream');
header($contentDispositionField);
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:
Cache-control:no-store
Cache-control:no-cache
See: http://support.microsoft.com/kb/323308
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/htmlNote that 'session_start' may overwrite your custom cache headers.
To remedy this you need to call:
session_cache_limiter('');
...after you set your custom cache headers. It will tell the PHP session code to not do any cache header changes of its own.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.
<?php
header("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.
<?php
header("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.
<?php
ob_start();
header("location: 1.html");
echo "send data";
header("location: 2.html"); //replaces 1.html
ob_end_flush(); //now the headers are sent
?>A call to session_write_close() before the statement
<?php
header("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).
JP.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');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.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.
<?php
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
?>