php set response header

Php set response header

Attempting to set headers after the document has started results in this warning:

7.5.1. Different Content Types

In Chapter 9 and Chapter 10, we’ll make heavy use of the Content-Type header as we generate documents that are really graphic images and Adobe PDF files.

7.5.2. Redirections

If you provide a partial URL (e.g., «/elsewhere.html»), the redirection is handled internally by the web server. This is only rarely useful, as the browser generally won’t learn that it isn’t getting the page it requested. If there are relative URLs in the new document, the browser will interpret them as being relative to the document it requested, not the document it was sent. In general, you’ll want to redirect to an absolute URL.

7.5.3. Expiration

To set the expiration time of a document, use the Expires header:

To expire a document three hours from the time the page was generated, use time( ) and gmstrftime( ) to generate the expiration date string:

To indicate that a document «never» expires, use the time a year from now:

To mark a document as already expired, use the current time or a time in the past:

This is the best way to prevent a browser or proxy cache from storing your document:

For more information on controlling the behavior of browser and web caches, see Chapter 6 of Web Caching, by Duane Wessels (O’Reilly).

7.5.4. Authentication

You can do anything you want to authenticate the username and password; for example, you could consult a database, read a file of valid users, or consult a Microsoft domain server. This example checks to make sure that the password is the username, reversed:

Putting this into a document gives something like:

If you’re protecting more than one page, put the above code into a separate file and include it at the top of every protected page.

php set response header. Смотреть фото php set response header. Смотреть картинку php set response header. Картинка про php set response header. Фото php set response header

Copyright © 2003 O’Reilly & Associates. All rights reserved.

Источник

PHP: How to send HTTP response code?

I have a PHP script that needs to make responses with HTTP response codes (status-codes), like HTTP 200 OK, or some 4XX or 5XX code.

How can I do this in PHP?

php set response header. Смотреть фото php set response header. Смотреть картинку php set response header. Картинка про php set response header. Фото php set response header

8 Answers 8

I just found this question and thought it needs a more comprehensive answer:

As of PHP 5.4 there are three methods to accomplish this:

Assembling the response code on your own (PHP >= 4.0)

The header() function has a special use-case that detects a HTTP response line and lets you replace that with a custom one

However, this requires special treatment for (Fast)CGI PHP:

Note: According to the HTTP RFC, the reason phrase can be any custom string (that conforms to the standard), but for the sake of client compatibility I do not recommend putting a random string there.

Note: php_sapi_name() requires PHP 4.0.1

3rd argument to header function (PHP >= 4.3)

There are obviously a few problems when using that first variant. The biggest of which I think is that it is partly parsed by PHP or the web server and poorly documented.

Since 4.3, the header function has a 3rd argument that lets you set the response code somewhat comfortably, but using it requires the first argument to be a non-empty string. Here are two options:

I recommend the 2nd one. The first does work on all browsers I have tested, but some minor browsers or web crawlers may have a problem with a header line that only contains a colon. The header field name in the 2nd. variant is of course not standardized in any way and could be modified, I just chose a hopefully descriptive name.

http_response_code function (PHP >= 5.4)

The http_response_code() function was introduced in PHP 5.4, and it made things a lot easier.

Compatibility

Here is a function that I have cooked up when I needed compatibility below 5.4 but wanted the functionality of the «new» http_response_code function. I believe PHP 4.3 is more than enough backwards compatibility, but you never know.

Unfortunately I found solutions presented by @dualed have various flaws.

Using substr($sapi_type, 0, 3) == ‘cgi’ is not enogh to detect fast CGI. When using PHP-FPM FastCGI Process Manager, php_sapi_name() returns fpm not cgi

There are at least 2 cases when calling http_response_code() result in unexpected behaviour:

For your reference here there is the full list of HTTP response status codes (this list includes codes from IETF internet standards as well as other IETF RFCs. Many of them are NOT currently supported by PHP http_response_code function): http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

You can easily test this bug by calling:

The server will send «500 Internal Server Error» HTTP response code resulting in unexpected errors if you have for example a custom client application calling your server and expecting some additional HTTP codes.

My solution (for all PHP versions since 4.1.0):

Conclusion

http_response_code() implementation does not support all HTTP response codes and may overwrite the specified HTTP response code with another one from the same group.

The new http_response_code() function does not solve all the problems involved but make things worst introducing new bugs.

The «compatibility» solution offered by @dualed does not work as expected, at least under PHP-FPM.

The other solutions offered by @dualed also have various bugs. Fast CGI detection does not handle PHP-FPM. Current protocol must be detected.

Источник

$http_response_header

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

$http_response_header — Заголовки ответов HTTP

Описание

Примеры

Результатом выполнения данного примера будет что-то подобное:

User Contributed Notes 5 notes

The cURL extension doesn’t have this limit.

http_fopen_wrapper.c: #define HTTP_HEADER_BLOCK_SIZE 1024

parser function to get formatted headers (with response code)

/*
Array
(
[0] => HTTP/1.1 200 OK
[reponse_code] => 200
[Date] => Fri, 01 May 2015 12:56:09 GMT
[Server] => Apache
[X-Powered-By] => PHP/5.3.3-7+squeeze18
[Set-Cookie] => PHPSESSID=ng25jekmlipl1smfscq7copdl3; path=/
[Expires] => Thu, 19 Nov 1981 08:52:00 GMT
[Cache-Control] => no-store, no-cache, must-revalidate, post-check=0, pre-check=0
[Pragma] => no-cache
[Vary] => Accept-Encoding
[Content-Length] => 872
[Connection] => close
[Content-Type] => text/html
)
*/

If an HTTP Redirect is encountered, the headers will contain the response line and headers for all requests encountered. Consider this example:

array(23) <
[0]=>
string(18) «HTTP/1.1 302 FOUND»
[1]=>
string(17) «Connection: close»
[2]=>
string(22) «Server: meinheld/0.6.1»
[3]=>
string(35) «Date: Tue, 06 Feb 2018 11:21:21 GMT»
[4]=>
string(38) «Content-Type: text/html; charset=utf-8»
[5]=>
string(17) «Content-Length: 0»
[6]=>
string(30) «Location: https://httpbin.org/»
[7]=>
string(30) «Access-Control-Allow-Origin: *»
[8]=>
string(38) «Access-Control-Allow-Credentials: true»
[9]=>
string(19) «X-Powered-By: Flask»
[10]=>
string(34) «X-Processed-Time: 0.00107908248901»
[11]=>
string(14) «Via: 1.1 vegur»
[12]=>
string(15) «HTTP/1.1 200 OK»
[13]=>
string(17) «Connection: close»
[14]=>
string(22) «Server: meinheld/0.6.1»
[15]=>
string(35) «Date: Tue, 06 Feb 2018 11:21:21 GMT»
[16]=>
string(38) «Content-Type: text/html; charset=utf-8»
[17]=>
string(21) «Content-Length: 13011»
[18]=>
string(30) «Access-Control-Allow-Origin: *»
[19]=>
string(38) «Access-Control-Allow-Credentials: true»
[20]=>
string(19) «X-Powered-By: Flask»
[21]=>
string(34) «X-Processed-Time: 0.00848388671875»
[22]=>
string(14) «Via: 1.1 vegur»
>

For this and other reasons I recommend PHP cURL, instead of file_get_contents().

Bear in mind this special variable is somehow protected and not populated in some situation when the peer server close the connection early on (ssl reset)
=> Undefined variable: http_response_header

Will return a cryptic error message:
Fatal error: Call to undefined function array() on line 2

Источник

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

Источник

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

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