How to post data in PHP using file_get_contents?

373,889

Solution 1

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

Solution 2

An alternative, you can also use fopen

$params = array('http' => array(
    'method' => 'POST',
    'content' => 'toto=1&tata=2'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp)
{
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if ($response === false) 
{
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}
Share:
373,889
Paras Chopra
Author by

Paras Chopra

Updated on July 08, 2022

Comments

  • Paras Chopra
    Paras Chopra almost 2 years

    I'm 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.

  • Paras Chopra
    Paras Chopra about 14 years
    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?
  • Pascal MARTIN
    Pascal MARTIN about 14 years
    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&param2=value2&param3=value3 ) ;; which means you'll probably have to use http_build_query($_POST)
  • Liam Newmarch
    Liam Newmarch over 12 years
    Wonderful! I was looking for a way to pass POST data to another page which is achievable by doing $postdata = http_build_query($_POST).
  • WojonsTech
    WojonsTech over 11 years
    intresting enough this does not work for me at all i been tryiung it for a few hours and all my requets get turned into get querys
  • oldergod
    oldergod almost 11 years
    What if the parameters value are not strings but arrays or hashes etc ?
  • rymo
    rymo almost 10 years
    To send multiple header values, throw them all into one string with \r\n line breaks - see: stackoverflow.com/a/2107792/404960
  • malisokan
    malisokan over 9 years
    Always add the option ignore_errors => true to get a more cURL like result. Otherwise file_get_contents will only return false, if there is an HTTP error status code delivered by the server. Just in case if you are working with some kind of API, which sets HTTP error status codes and you want to analyse the received message or error details.
  • Michael Yaworski
    Michael Yaworski almost 9 years
    For some reason, this worked for me, but the PHP official example did not. +1 for the toto=1&tata=2 as well. I didn't use the fopen, however.
  • Daedalus
    Daedalus over 8 years
    @Ġiĺàɗ We don't call people 'noob' here. This is a friendly warning against such.
  • Volomike
    Volomike almost 8 years
    To send raw XML post, change header to Content-Type: text/plain or Content-Type: text/xml and then set content to the XML. In my case, I usually don't send raw, unencrypted XML. I usually use openssl_encrypt with aes-256-cbc and a long password. But your needs may vary.
  • Louys Patrice Bessette
    Louys Patrice Bessette about 7 years
    As of 2017: No matter all comments... This original answer is working SUPER GREAT. My only issue was NOT TO USE relative path to the target file to open, but the full URL. +1 (I'm using this to get email templates in different langages) ;)
  • w5m
    w5m almost 7 years
    Superb - I've never seen this technique before - I used it to POST JSON to a REST API and retrieve a JSON response.
  • Felipe Leão
    Felipe Leão about 6 years
    Please, try to provide an elaborated answer instead of simply copying/pasting code.
  • Cristal
    Cristal about 6 years
    Is it possible to do this using curl?
  • Martin Prikryl
    Martin Prikryl over 5 years
    Also this is unnecessarily complicated. You can use file_get_contents instead of fopen + stream_get_contents. And you are not even closing the "file". See the accepted answer by @PascalMARTIN.