Sometimes, we want to post data in PHP using file_get_contents
In this article, we’ll look at how to post data in PHP using file_get_contents.
How to post data in PHP using file_get_contents?
To post data in PHP using file_get_contents, we can call file_get_contents
with an options array.
For instance, we write
$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);
to create the $postdata
object with the form data parameter values.
We call http_build_query
to build the query string.
Then we have the $opts
array that sets the request method, request headers, and the content.
Then we call stream_context_create
with $opts
to create the $context
object.
And then we call file_get_contents
with the URL to make the request to and the $context
object to make the request.
Finally, we get the response returned from file_get_contents
and we assign it to $result
.
Conclusion
To post data in PHP using file_get_contents, we can call file_get_contents
with an options array.