php header location server self

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

Источник

PHP: Utilizing exit(); or die(); after header(«Location: «);

I have a user login/registration system that simply uses

I recently read a post about exit(); and die(); and had no idea that I was supposed to be using these. From what I understand, they make it end the PHP? Is that correct? What’s the best way I can work toward this, simply adding one of these functions directly after ever header(); execution I have?

I have AJAX, jQuery reading through my login.php/register.php, will this be affect in any way?

Edit: Other than after header();, where else should I be usitilizing the exit(); or die(); functions? And is exit(); more used around PHP whereas die(); more used around Perl?

6 Answers 6

I have been looking for an answer on this as well. What I found:

Why die() or exit():

If you don’t put a die() or exit() after your header(‘Location: http://something’) your script may continue resulting in unexpected behaviour. This may for example result in content being disclosed that you actually wanted to prevent with the redirect (HTTP 301). The aforementioned may not directly be visible for an end user as the browser may not render it (due to the 301). Conclusion, the exit() and die() functions stop the script from continuing.

Difference:

I also wanted to know the difference between the functions as it seems there is none. However, in PHP, there is a distinct difference in Header output. In the examples below I chose to use a different header but for sake of showing the difference between exit() and die() that doesn’t matter.

Exit() in action

Die() in action

Difference

So, die() closes the connection and exit() doesn’t. It depends on performance whether or not you want to keep the connection open or close it. Both have advantages and disadvantages and depends on your specific requirement(s).

Answer has already been accepted however it seems everyone is missing the glaring WTF in the question:

Returning a referer is optional on the part of the user agent

it can easily be faked

there is no method for telling the user the login has failed

there is no HTTP semantic communication of an authentication failure

while the environment variable HTTP_REFERER should be the same as the request header variable, it is not specified in RFC 3875, therefore even where presented to the webserver in the request, getenv(«HTTP_REFERER») may return a different value

Ok, it has been a long time since the last answer was given. Anyway 😀 somehow I stumbled across a similar prob and see what my solution was:

php header location server self. Смотреть фото php header location server self. Смотреть картинку php header location server self. Картинка про php header location server self. Фото php header location server self

php header location server self. Смотреть фото php header location server self. Смотреть картинку php header location server self. Картинка про php header location server self. Фото php header location server self

Now let us look at the same example using die();

The output for each of these will be: “Using exit(), We are done Using die(), We are done” respectively. Now let us try each of these to output a number.

Looking at the output for the same example using die();

So, the honest answer to the question “What is difference between die() and exit() in php” IS – There is not a single visible difference between these two functions. They both are the same, one is the alias of the other. If at all any one of you can find a real visible difference then I would appreciate if you could post it in the comments section of this blog.

Источник

It works when I input

but it doesn’t work when I have

I want to redirect the page to whatever page it came from.

php header location server self. Смотреть фото php header location server self. Смотреть картинку php header location server self. Картинка про php header location server self. Фото php header location server self

7 Answers 7

However, for determining which page user came from, I’d rather use session variable, which gets reset at every page:

ps: This only works for local pages, you cannot track other websites.

I’ve had problems with variable expressions which contain quotes in strings without braces.

This is a browser feature, and any polite browser will send the correct header (although various ‘security’ tools will override this with a fake referer).

It’s browser specific so not every browser/security software combination will send it to the server. You’re better off setting a session variable on each page load to determine which page the user came from (or something similar with a bit more logic)

Without the single quotes. This is the fastest way to access and concatenate array values without extra concatenating code.

Simply you can use

php header location server self. Смотреть фото php header location server self. Смотреть картинку php header location server self. Картинка про php header location server self. Фото php header location server self

php header location server self. Смотреть фото php header location server self. Смотреть картинку php header location server self. Картинка про php header location server self. Фото php header location server self

This is not working (shows the output, but doesn’t redirect):

This is working (does redirect properly):

This is also working, but doesn’t make sense ():

(For better understandig, hope this may help)

Источник

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

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