Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiple headers to file_get_content in PHP

Tags:

php

$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.

like image 511
Aman Jain Avatar asked Nov 29 '22 07:11

Aman Jain


2 Answers

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().

like image 32
Volomike Avatar answered Nov 30 '22 20:11

Volomike


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.

like image 74
dotancohen Avatar answered Nov 30 '22 20:11

dotancohen