$opts = array('http' => array('method' => $_SERVER['REQUEST_METHOD'],
'header' => array("Accept-language: en\r\n",
"Cookie: " . session_name() . "=" . session_id() . "\r\n",
" Content-type: application/x-www-form-urlencoded\r\n"),
'content' => $_POST));
$postdata = http_build_query($_POST);
$context = stream_context_create($opts);
session_write_close(); // This is the key
echo $obsah = file_get_contents("http://localhost/journal/", false, $context);
This code is not working with POST and cookies.
When passing a header with an array()
instead of a string, you don't need the \r\n
because PHP's stream_context_create()
will do it for you on the header.
You also don't need session_write_close()
.
The two existing answers are incorrect.
Newlines (\n
) do not need to be added to HTTP headers used in stream_context_create()
, and furthermore Carriage Returns (\r
) should never be used anywhere near HTTP.
The following code is copied from the OP and corrected:
$postdata = http_build_query($_POST, '', '&', PHP_QUERY_RFC3986);
$opts = array(
'http' => array(
'method' => $_SERVER['REQUEST_METHOD'],
'header' => array(
"Accept-language: en",
"Cookie: " . session_name() . "=" . session_id(),
"Content-type: application/x-www-form-urlencoded",
),
'content' => $postdata,
)
);
$context = stream_context_create($opts);
$obsah = file_get_contents("http://localhost/journal/", false, $context);
echo $obsah
I've also added commas to the last array items so that maintenance will not have unnecessary lines in Git / SVN commits, and configured http_build_query() to use the more modern RFC 3986 encoding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With