How to post data in PHP using file_get_contents?
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");
}
Paras Chopra
Updated on July 08, 2022Comments
-
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 about 14 yearsThanks. 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 about 14 yearsI 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¶m2=value2¶m3=value3
) ;; which means you'll probably have to usehttp_build_query($_POST)
-
Liam Newmarch over 12 yearsWonderful! I was looking for a way to pass POST data to another page which is achievable by doing
$postdata = http_build_query($_POST)
. -
WojonsTech over 11 yearsintresting 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 almost 11 yearsWhat if the parameters value are not strings but arrays or hashes etc ?
-
rymo almost 10 yearsTo send multiple header values, throw them all into one string with
\r\n
line breaks - see: stackoverflow.com/a/2107792/404960 -
malisokan over 9 yearsAlways add the option ignore_errors => true to get a more cURL like result. Otherwise
file_get_contents
will only returnfalse
, 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 almost 9 yearsFor 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 thefopen
, however. -
Daedalus over 8 years@Ġiĺàɗ We don't call people 'noob' here. This is a friendly warning against such.
-
Volomike almost 8 yearsTo send raw XML post, change
header
toContent-Type: text/plain
orContent-Type: text/xml
and then setcontent
to the XML. In my case, I usually don't send raw, unencrypted XML. I usually useopenssl_encrypt
withaes-256-cbc
and a long password. But your needs may vary. -
Louys Patrice Bessette about 7 yearsAs 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 almost 7 yearsSuperb - 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 about 6 yearsPlease, try to provide an elaborated answer instead of simply copying/pasting code.
-
Cristal about 6 yearsIs it possible to do this using curl?
-
Martin Prikryl over 5 yearsAlso this is unnecessarily complicated. You can use
file_get_contents
instead offopen
+stream_get_contents
. And you are not even closing the "file". See the accepted answer by @PascalMARTIN.