views:

1646

answers:

1

I am using PHP's function file_get_contents() to fetch contents of a URL and then I process headers through the variable $http_response_header. Now the problem is that some of the URLs need some data to be posted to the URL (for example, login pages). How do I do that?

I realize using stream_context I may be able to do that but I am not entirely clear.

Thanks.

+11  A: 

Sending an HTTP POST request using file_get_contents is not that hard, actually : as you guessed, you have to use the $context parameter.


There's an example given in the PHP manual, at this page : HTTP context options (quoting) :

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

Basically, you have to create a stream, with the right options (there is a full list on that page), and use it as the third parameter to file_get_contents -- nothing more ;-)


As a sidenote : generally speaking, to send HTTP POST requests, we tend to use curl, which provides a lot of options an all -- but streams are one of the nice things of PHP that nobody knows about... too bad...

Pascal MARTIN
Thanks. I am guessing I can insert the contents from $_POST into $postdata if I need to pass same POST params to the requested page?
Paras Chopra
I suppose you can do something like that ; but `content` must not be a PHP array : it has to be a querystring *(i.e. it must has this format : `param1=value1; which means you'll probably have to use `http_build_query($_POST)`
Pascal MARTIN