Php post response header

$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+(9+)#» , $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

Источник

GET, POST, and HEAD requests with PHP’s build-in functions

How to send HTTP requests using the build-in file functions of PHP.

d

PHP article image

There are a few ways to perform HTTP requests in PHP, in this tutorial we will show how to send a POST and GET request by using the file- functions in combination with stream_context_create.

While using a library like cURL is probably one of the most popular ways to perform HTTP requests, you can also use functions such as file_get_contents and fopen.

While the name of these functions do not exactly indicate that they can also be used for HTTP requests, they do actually work quite well for this, and they are also fairly easy to use.

The stream_context_create function mentioned before is used to gain finer control over various options related to a request.

There should be no disadvantage to using the build-in functions instead of cURL, and unlike what is often claimed, they can be used for both POST and GET requests. However, some hosting companies might disable allow_url_fopen, which will break scripts relying on these methods.

GET Requests

To perform a simple get request, we will first create a $handle variable. We can use this to reference the request when storing the downloaded data in the $contents variable using stream_get_contents.

$handle = fopen("https://beamtic.com/", "rb"); $contents = stream_get_contents($handle); fclose($handle); 

The stream_get_contents function automatically downloads a file or web page, however, if you wish to do it manually, for finer control over the process, you may use a while loop in combination with fread:

$handle = fopen("https://beamtic.com/", "rb"); $contents = ''; while (!feof($handle))  $contents .= fread($handle, 8192); > fclose($handle); echo $contents; 

In this case the last argument in the fread function is equal to the chunk size, this is usually not larger than 8192 (8*1024). Keep in mind that this can be larger or smaller, but may also be limited by the system PHP is running on. You can optimize your PHP scripts by not using a larger chunk-size than that of your storage device.

One of the simplest ways to download a file, is to use file_get_contents. It requires far less code than using the other methods, but it also offers less control over the process.

$homepage = file_get_contents('https://beamtic.com/'); echo $homepage; 

POST Requests

Sending a POST request is not much harder than sending GET. We just have to use the stream_context_create function to add the necessary headers to perform the request.

Again, we can do this both with file_get_contents and fopen; but let us just use file_get_contents for now:

$sURL = "https://beamtic.com/Examples/http-post.php"; // The POST URL $sPD = "name=Jacob&bench=150"; // The POST Data $aHTTP = array( 'http' => // The wrapper to be used array( 'method' => 'POST', // Request Method // Request Headers Below 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $sPD ) ); $context = stream_context_create($aHTTP); $contents = file_get_contents($sURL, false, $context); echo $contents; 

The $sURL variable contains the POST URL.

The $sPD variable contains the data you want to post. Formatting should match the content-type header.

The $aHTTP array has all of the options, including headers, which will be passed on to stream_context_create.

You can also perform POST requests with the fread function.

$sURL = "http://beamtic.com/Examples/http-post.php"; // The POST URL $sPD = "name=Jacob&bench=150"; // The POST Data $aHTTP = array( 'http' => // The wrapper to be used array( 'method' => 'POST', // Request Method // Request Headers Below 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $sPD ) ); $context = stream_context_create($aHTTP); $handle = fopen($sURL, 'r', false, $context); $contents = ''; while (!feof($handle))  $contents .= fread($handle, 8192); > fclose($handle); echo $contents; 

Request Headers

If you got multiple headers, remember to separate them with \r\n

The content-type header tells the server how the posted data is formatted. The application/x-www-form-urlencoded content-type is often used by web applications, but you can also encounter multipart/form-data. If an application does not support the content-type you specify, the POST will usually just fail.

The content header contains the actual data that you want to post. This should be formatted in accordance with the content-type you are using.

Alternatively, you may also add options and headers as shown below, this time adding a referer header:

$aHTTP['http']['method'] = 'GET'; $aHTTP['http']['header'] = "User-Agent: My PHP Script\r\n"; $aHTTP['http']['header'] .= "Referer: https://beamtic.com/\r\n"; 

Additional request headers will be added in the same way; do this by adding a single Carriage return (\r), and a line feed (\n) at the end of each header, followed by whatever header you want to add. Once you have added all the headers, you should end up with something like the below (full script):

$sURL = "https://beamtic.com/api/request-headers"; // The POST URL $aHTTP['http']['method'] = 'GET'; $aHTTP['http']['header'] = "User-Agent: My PHP Script\r\n"; $aHTTP['http']['header'] .= "Referer: https://beamtic.com/\r\n"; $context = stream_context_create($aHTTP); $contents = file_get_contents($sURL, false, $context); echo $contents; 

Tools:

You can use the following API endpoints for testing purposes:

https://beamtic.com/api/user-agent
https://beamtic.com/api/request-headers

Источник

Читайте также:  Как создать класс в java vs code
Оцените статью