note 108261 rejected from function.stream-context-create by mazzanet
| From: | mazzanet@php.net | Date: | Fri, 13 Apr 2012 03:16:55 +0000 |
| Subject: | note 108261 rejected from function.stream-context-create by mazzanet | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-187099@lists.php.net to get a copy of this message | ||
Note Submitter: moazzam at moazzam-khan dot com
----
If you do an HTTP post request to using a stream context, and the server returns a 302, then PHP
makes a GET request to the location specified in the response headers.
client.php (the PHP code that makes the HTTP request)
==================
<?php
function runRequest($verb, $uri, $data)
$params = array(
'http' => array(
'method' => $verb,
'ignore_errors' => true,
'header' => "Accept: application/json\r\n"
. "Cache-Control: no-cache\r\n"
. "Pragma: no-cache\r\n"
)
);
if ($verb == 'POST') {
if (is_array($data)) {
$str = http_build_query($data);
} else {
$str = $data;
}
$params['http']['header'] .= "Content-type:
application/x-www-form-urlencoded\r\n"
. 'Content-Length: '.strlen($str)."\r\n";
$params['http']['content'] = $str;
}
$ctx = stream_context_create($params);
$fp = @fopen($uri, 'rb', false, $ctx);
if (!$fp) {
print "runReq.fail:$verb-$uri";
// throw new Exception('Problem with '.$verb.' '.$uri);
}
$output = @stream_get_contents($fp);
$headers = @stream_get_meta_data($fp);
fclose($fp);
unset($fp);
unset($ctx);
unset($str);
unset($params);
// unset($verb);
var_dump($headers);
var_dump($output);
}
?>
a.php (does the redirect)
============
<?php
header('Location: /b.php', true, 302);
?>
b.php
=================
<?php
var_dump($_REQUEST);
var_dump($_SERVER);
?>
When I run client.php, this is the response:
...truncated ...
["SERVER_ADMIN"]=>
string(15) "you@example.com"
["SCRIPT_FILENAME"]=>
string(26) "/Users/moz/Sites/exp/b.php"
["REMOTE_PORT"]=>
string(5) "56070"
["GATEWAY_INTERFACE"]=>
string(7) "CGI/1.1"
["SERVER_PROTOCOL"]=>
string(8) "HTTP/1.0"
["REQUEST_METHOD"]=>
string(3) "GET"
["QUERY_STRING"]=>
string(0) ""
["REQUEST_URI"]=>
string(6) "/b.php"
["SCRIPT_NAME"]=>
string(6) "/b.php"
["PHP_SELF"]=>
string(6) "/b.php"
["REQUEST_TIME"]=>
int(1334249770)
}
array(0) {
}
array(5) {
["Host"]=>
string(8) "expo.dev"
["Accept"]=>
string(16) "application/json"
["Cache-Control"]=>
string(8) "no-cache"
["Pragma"]=>
string(8) "no-cache"
["Content-type"]=>
string(33) "application/x-www-form-urlencoded"
}
"
As you guys can see, the POST request became a GET request when it got to b.php
Just something to keep in mind if you're making a REST web application