Php file get contents get response headers

Get Response Header from file_get_contents in PHP

file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.

A URL can be used as a filename with this function if the fopen wrappers have been enabled.

But, reading URL becomes difficult to identify that URL is not available. And if URL is not available, it’s also difficult to process that URL. So, it is necessary that there is a response for every request fired by file_get_contents() for any URL.

PHP has a predefined variable named $http_response_header, which provides a response header for any HTTP request sent by PHP code.

file_get_contents("http://example.com"); var_dump($http_response_header);

The above example will output something similar to:

array(9) < [0]=>string(15) "HTTP/1.1 200 OK" [1]=> string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT" [2]=> string(29) "Server: Apache/2.2.3 (CentOS)" [3]=> string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT" [4]=> string(27) "ETag: "280100-1b6-80bfd280"" [5]=> string(20) "Accept-Ranges: bytes" [6]=> string(19) "Content-Length: 438" [7]=> string(17) "Connection: close" [8]=> string(38) "Content-Type: text/html; charset=UTF-8" >

Note that the HTTP wrapper has a hard limit of 1024 characters for the header lines.
Any HTTP header received that is longer than this will be ignored and won’t appear in $http_response_header.

The cURL extension doesn’t have this limit.

Источник

$http_response_header

The $http_response_header array is similar to the get_headers() function. When using the HTTP wrapper, $http_response_header will be populated with the HTTP response headers. $http_response_header will be created in the local scope.

Examples

Example #1 $http_response_header example

function get_contents () file_get_contents ( «http://example.com» );
var_dump ( $http_response_header );
>
get_contents ();
var_dump ( $http_response_header );
?>

The above example will output something similar to:

array(9) < [0]=>string(15) "HTTP/1.1 200 OK" [1]=> string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT" [2]=> string(29) "Server: Apache/2.2.3 (CentOS)" [3]=> string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT" [4]=> string(27) "ETag: "280100-1b6-80bfd280"" [5]=> string(20) "Accept-Ranges: bytes" [6]=> string(19) "Content-Length: 438" [7]=> string(17) "Connection: close" [8]=> string(38) "Content-Type: text/html; charset=UTF-8" > NULL

User Contributed Notes 5 notes

Note that the HTTP wrapper has a hard limit of 1024 characters for the header lines.
Any HTTP header received that is longer than this will be ignored and won’t appear in $http_response_header.

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)

function parseHeaders ( $headers )
$head = array();
foreach( $headers as $k => $v )
$t = explode ( ‘:’ , $v , 2 );
if( isset( $t [ 1 ] ) )
$head [ trim ( $t [ 0 ]) ] = trim ( $t [ 1 ] );
else
$head [] = $v ;
if( preg_match ( «#HTTP/[0-9\.]+\s+(3+)#» , $v , $out ) )
$head [ ‘reponse_code’ ] = intval ( $out [ 1 ]);
>
>
return $head ;
>

print_r ( parseHeaders ( $http_response_header ));

/*
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
)
*/

It seems that, if the server returns an HTTP/1.1 100 Continue, the variable $http_response_header is unset. This corner case may be difficult to be detected.

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

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»
>

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


Should you want to cope with this situation:
$hdrs = array(‘HTTP/1.1 400 Bad request’);
!empty($htp_response_header) && $hdrs = $http_response_headers;

Now use $hdrs in place of $http_response_header

Источник

file_get_contents

This function is similar to file() , except that file_get_contents() returns the file in a string , starting at the specified offset up to length bytes. On failure, file_get_contents() will return false .

file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.

Note:

If you’re opening a URI with special characters, such as spaces, you need to encode the URI with urlencode() .

Parameters

Note:

The FILE_USE_INCLUDE_PATH constant can be used to trigger include path search. This is not possible if strict typing is enabled, since FILE_USE_INCLUDE_PATH is an int . Use true instead.

A valid context resource created with stream_context_create() . If you don’t need to use a custom context, you can skip this parameter by null .

The offset where the reading starts on the original stream. Negative offsets count from the end of the stream.

Seeking ( offset ) is not supported with remote files. Attempting to seek on non-local files may work with small offsets, but this is unpredictable because it works on the buffered stream.

Maximum length of data read. The default is to read until end of file is reached. Note that this parameter is applied to the stream processed by the filters.

Return Values

The function returns the read data or false on failure.

This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Errors/Exceptions

An E_WARNING level error is generated if filename cannot be found, length is less than zero, or if seeking to the specified offset in the stream fails.

When file_get_contents() is called on a directory, an E_WARNING level error is generated on Windows, and as of PHP 7.4 on other operating systems as well.

Changelog

Version Description
8.0.0 length is nullable now.
7.1.0 Support for negative offset s has been added.

Examples

Example #1 Get and output the source of the homepage of a website

Example #2 Searching within the include_path

// If strict types are enabled i.e. declare(strict_types=1);
$file = file_get_contents ( ‘./people.txt’ , true );
// Otherwise
$file = file_get_contents ( ‘./people.txt’ , FILE_USE_INCLUDE_PATH );
?>

Example #3 Reading a section of a file

// Read 14 characters starting from the 21st character
$section = file_get_contents ( ‘./people.txt’ , FALSE , NULL , 20 , 14 );
var_dump ( $section );
?>

The above example will output something similar to:

Example #4 Using stream contexts

// Create a stream
$opts = array(
‘http’ =>array(
‘method’ => «GET» ,
‘header’ => «Accept-language: en\r\n» .
«Cookie: foo=bar\r\n»
)
);

$context = stream_context_create ( $opts );

// Open the file using the HTTP headers set above
$file = file_get_contents ( ‘http://www.example.com/’ , false , $context );
?>

Notes

Note: This function is binary-safe.

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as «SSL: Fatal Protocol Error» when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning.

See Also

  • file() — Reads entire file into an array
  • fgets() — Gets line from file pointer
  • fread() — Binary-safe file read
  • readfile() — Outputs a file
  • file_put_contents() — Write data to a file
  • stream_get_contents() — Reads remainder of a stream into a string
  • stream_context_create() — Creates a stream context
  • $http_response_header

User Contributed Notes 6 notes

file_get_contents can do a POST, create a context for that first:

$opts = array( ‘http’ =>
array(
‘method’ => ‘POST’ ,
‘header’ => «Content-Type: text/xml\r\n» .
«Authorization: Basic » . base64_encode ( » $https_user : $https_password » ). «\r\n» ,
‘content’ => $body ,
‘timeout’ => 60
)
);

$context = stream_context_create ( $opts );
$url = ‘https://’ . $https_server ;
$result = file_get_contents ( $url , false , $context , — 1 , 40000 );

Note that if an HTTP request fails but still has a response body, the result is still false, Not the response body which may have more details on why the request failed.

There’s barely a mention on this page but the $http_response_header will be populated with the HTTP headers if your file was a link. For example if you’re expecting an image you can do this:

$mimetype = null ;
foreach ( $http_response_header as $v ) if ( preg_match ( ‘/^content\-type:\s*(image\/[^;\s\n\r]+)/i’ , $v , $m )) $mimetype = $m [ 1 ];
>
>

if (! $mimetype ) // not an image
>

if the connection is
content-encoding: gzip
and you need to manually ungzip it, this is apparently the key
$c=gzinflate( substr($c,10,-8) );
(stolen from the net)

//从指定位置获取指定长度的文件内容
function file_start_length($path,$start=0,$length=null) if(!file_exists($path)) return false;
$size=filesize($path);
if($start <0) $start+=$size;
if($length===null) $length=$size-$start;
return file_get_contents($path, false, null, $start, $length );
>

I’m not sure why @jlh was downvoted, but I verified what he reported.

>>> file_get_contents($path false, null, 5, null)
=> «»
>>> file_get_contents($path, false, null, 5, 5)
=> «r/bin»

Источник

Читайте также:  Алгоритм водораздела opencv python
Оцените статью