php http request header
apache_request_headers
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
apache_request_headers — Получает список всех заголовков HTTP-запроса
Описание
Получает список всех заголовков HTTP текущего запроса. Работает на веб-серверах Apache и FastCGI.
Список параметров
У этой функции нет параметров.
Возвращаемые значения
Ассоциативный массив, содержащий все HTTP-заголовки текущего запроса, или false в случае возникновения ошибки.
Список изменений
Версия | Описание |
---|---|
7.3.0 | Эта функция стала доступна в SAPI FPM. |
Примеры
Пример #1 Пример использования apache_request_headers()
Результатом выполнения данного примера будет что-то подобное:
Примечания
Смотрите также
User Contributed Notes 5 notes
I didn’t found a replacement for apache_request_headers() in PHP::Compat (http://pear.php.net/package/PHP_Compat) so I wrote my own:
Although we expect to see headers in mixed case, the standard RFC2616 demands that «field names are case-insensitive». PHP delivers the headers exactly untouched in whatever way the client sent them. Potentially you should expect to get any type of uppercase or lowercase or mixed.
Thus, if you want to be standards compliant, you must loop through every key and check it in a case-insensitive manner, instead of doing the obvious thing and using the name of the header as an array index.
The headers are then available in PHP as
[ ‘HTTP_IF_MODIFIED_SINCE’ ];
$_SERVER [ ‘HTTP_IF_NONE_MATCH’ ];
?>
I’ve tested this on PHP/5.1.6, on both Apache/2.2.3/Win32 and Apache/2.0.54/Unix, and it works perfectly.
Note: if you use RewriteRules already for clean URLs, you need to put the above rules AFTER your existing ones.
A slightly modified version from limalopex.eisfux.de. Fixes the missing Headers Content-Type and Content-Length and makes it Camel-Case.
get_headers
get_headers — Возвращает все заголовки из ответа сервера на HTTP-запрос
Описание
get_headers() возвращает массив с заголовками из ответа сервера на HTTP-запрос.
Список параметров
Если необязательный параметр associative установлен в ненулевое значение, get_headers() разберёт ответ сервера и установит ключи для возвращаемого массива.
Возвращаемые значения
Возвращает индексированный или ассоциативный массив с заголовками ответа или false при возникновении ошибки.
Список изменений
Примеры
Пример #1 Пример использования get_headers()
Результатом выполнения данного примера будет что-то подобное:
Пример #2 Пример использования запроса HEAD в функции get_headers()
Смотрите также
User Contributed Notes 27 notes
If the URL redirected and the new target is also redirected, we got the Locations in array. Also we got the HTTP codes in a number indexed values.
array
(
[0] => HTTP/1.1 302 Moved Temporarily
[Location] => Array
(
[0] => /test.php?id=2
[1] => /test.php?id=3
[2] => /test.php?id=4
)
[1] => HTTP/1.1 302 Moved Temporarily
[2] => HTTP/1.1 302 Moved Temporarily
[3] => HTTP/1.1 200 OK
)
In a typical situation we need only the landing page information, so here is a small code to get it:
How to check if a url points to a valid video
I know you’re not supposed to reference other notes, but sincere props to Nick at Innovaweb’s comment, for which I base this addition to his idea:
If you use that function, it will return a string, which is great if you are checking for only files that return 404, or 200, or whatnot. If you cast the string value to an integer, you can perform mathematical comparison on it.
if( intval ( get_http_response_code ( ‘filename.jpg’ )) 400 ) <
// File exists, huzzah!
>
?>
Rule of thumb is if the response is less than 400, then the file’s there, even if it doesn’t return 200.
if the URL does not exist, it returns incomplete headers, making the substring default to rubbish.
The integer value of rubbish is always 0. So your lower than 400 does not always means it exists!
To check URL validity, this has been working nicely for me:
If you don’t want to display Warning when get_headers() function fails, you can simply add at-sign (@) before it.
// in failure, Warning will be hidden and false returned
$withoutWarning = @ get_headers ( «http://www.some-domain.com» );
// in failure, Warning displays and false will be returned, too
$withWarning = get_headers ( «http://www.some-domain.com» );
Note that get_headers should not be used against a URL that was gathered via user input. The timeout option in the stream context only affects the idle time between data in the stream. It does not affect connection time or the overall time of the request.
(Unfortunately, this is not mentioned in the docs for the timeout option, but has been discussed in a number of code discussions elsewhere, and I have done my own tests to confirm the conclusions of those discussions.)
If you are publishing your code, even default_socket_timeout cannot be relied on to remedy this, because it is broken for the HTTPS protocol on many but the more recent versions of PHP: https://bugs.php.net/bug.php?id=41631
With get_headers accepting user input, it can be very easy for an attacker to make all of your PHP child processes become busy.
Instead, use cURL functions to get headers for a URL provided by the user and parse those headers manually, as CURLOPT_TIMEOUT applies to the entire request.
hey, i came across this afew weeks ago and used the function in an app for recording info about domains that my company owns, and found that the status this returns was wrong most of the time (400 bad request or void for sites that were clearly online). then looking into it i noticed the problem was that it wasn’t able to get the correct info about sites with redirections. but thats not the full problem because everything on my server was returning the wrong status too. i searched around on php.net for other info and found that fsockopen’s example worked better and only needed some tweeking.
heres the function i put together from it and a small change.
hope this’ll help someone else.
It should be noted that rather than returning «false» on failure, this function (and others) return a big phat WARNING that will halt your script in its tracks if you do not have error reporting /warning turned off.
Thats just insane! Any function that does something like fetch a URL should simply return false, without a warning, if the URL fails for whatever reason other than it is badly formatted.
The following code dose NOT work with PHP version 7.0.26 with my server.
Some other setting may be required?
Tried with website pages and path to local files.
The word ‘Finished’ is printed only.
Should be the same than the original get_headers():
I’ve noticed it.
Some Server will simply return the false reply header if you sent ‘HEAD’ request instead of ‘GET’. The ‘GET’ request header always receiving the most actual HTTP header instead of ‘HEAD’ request header. But If you don’t mind for a fast but risky method then ‘HEAD’ request is better for you.
aeontech, this the below change adds support for SSL connections. Thanks for the code!
I found that this function is the slowest in obtaining the headers of a page probably because it uses a GET request rather then a HEAD request. Over 10,000,000 trials of obtaining the headers of a page from a server i found the following (results in seconds).
cURL: Mean: 0.584127946. Sigma: 0.050581736.
fsocketopen: Mean: 0.622114251. Sigma: 0.263170424.
get_headers: Mean: 0.90375551. Sigma: 0.273823419.
cURL was the fastest with fsocketopens being the second fastest. I noticed as well that fsocketopen had some outliers where as cURL did not.
In some cases, you don’t want get_headers to follow redirects. For example, some of my servers can access a particular website, which sends a redirect header. The site it is redirected to, however, has me firewalled. I need to take the 302 redirected url, and do something to it to give me a new url that I *can* connect to.
The following will give you output similar to get_headers, except it has a timeout, and it doesn’t follow redirects:
Testing the validity of a URL that is preceded by one or more server redirects is tricky. There will be more than one status code returned and all but the first will be redirect codes.
This function will return an integer containing the three digit status code of the last code returned, which is what you want.
return (int) substr($value, strpos($value, ‘ ‘, 8) + 1, 3);
>
If getHeaders() fails, PHP will throw an error. Test the return value for === false.
/**
* Fetches all the real headers sent by the server in response to a HTTP request without redirects
*
* @link http://php.net/function.get_headers
* @link http://bugs.php.net/bug.php?id=50719
*/
For anyone reading the previous comments, here is code that takes into account all the previous suggestions and includes a bugfix, too.
In response to dotpointer’s modification of Jamaz’ solution.
if(! function_exists ( ‘get_headers’ )) <
Unfortunately there is still no useful output format to handle redirects.
This function will bring all non-broken headers into a usable format. Too bad it has to call the get_headers() funtion 2 times, but i dont see any other possibility right now.
Content-Type returns a value depending only on the extension and not the real MIME TYPE.
Как прочитать заголовок запроса в PHP
Как я должен читать любой заголовок в PHP?
14 ответов
если: вам нужен только один заголовок, вместо все заголовки, самый быстрый метод-это:
ТО ЕСЛИ: вы запускаете PHP как модуль Apache или, начиная с PHP 5.4, используя FastCGI (простой метод):
другое: в любом другом случае вы можете использовать (реализация userland):
к примеру X-Requested-With можно найти в:
начиная с PHP 5.4.0 вы можете использовать getallheaders функция, которая возвращает все запрошенные заголовки в виде ассоциативного массива:
ранее эта функция работала только тогда, когда PHP работал как модуль Apache/NSAPI.
strtolower отсутствует в нескольких предлагаемых решениях, RFC2616 (HTTP/1.1) определяет поля заголовка как объекты, нечувствительные к регистру. Все это, а не только стоимостью часть.
поэтому предложения, как только разбор соответствующий http_ записи неверны.
обратите внимание на тонкие различия с предыдущими предложениями. Функция здесь также работает на php-fpm (+nginx).
передать ключ заголовка эта функция вернет его значение вы можете получить значение заголовка с помощью for loop
чтобы сделать вещи простыми, вот как вы можете получить только один вы хотите:
или когда вам нужно получить по одному за раз:
я использовал CodeIgniter и использовал код ниже, чтобы получить его. Может пригодиться кому-то в будущем.
это выглядит намного проще, чем большинство примеров, приведенных в других ответах. Это также получает метод (GET/POST / etc.) и URI, запрошенный при получении всех заголовков, которые могут быть полезны, если вы пытаетесь использовать его в журнале.
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