Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post data in PHP using file_get_contents?

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.

like image 571
Paras Chopra Avatar asked Mar 15 '10 05:03

Paras Chopra


People also ask

What is the use of file_get_contents () function?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.

What will the file_get_contents () return?

The file_get_contents() function returns Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. An E_WARNING level error is generated if filename cannot be found, maxlength is less than zero, or if seeking the specified offset in the stream fails.

Which is faster curl or file_get_contents?

Curl is a much faster alternative to file_get_contents. Using file_get_contents to retrieve http://www.knowledgecornor.com/ took 0.198035001234 seconds. Meanwhile, using curl to retrieve the same file took 0.025691986084 seconds. As you can see, curl is much faster.

How do I echo content in PHP?

readfile("/path/to/file"); This will read the file and send it to the browser in one command. This is essentially the same as: echo file_get_contents("/path/to/file");


1 Answers

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

like image 68
Pascal MARTIN Avatar answered Sep 30 '22 02:09

Pascal MARTIN