Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send a POST request with PHP?

Actually I want to read the contents that come after the search query, when it is done. The problem is that the URL only accepts POST methods, and it does not take any action with GET method...

I have to read all contents with the help of domdocument or file_get_contents(). Is there any method that will let me send parameters with POST method and then read the contents via PHP?

like image 480
Fred Tanrikut Avatar asked Apr 13 '11 10:04

Fred Tanrikut


People also ask

How get post API in PHP?

To make a POST request to an API endpoint, you need to send an HTTP POST request to the server and specify a Content-Type request header that specifies the data media type in the body of the POST request. The Content-Length header indicates the size of the data in the body of the POST request.

How post URL in PHP?

If you're looking to post data to a URL from PHP code itself (without using an html form) it can be done with curl. It will look like this: $url = 'http://www.someurl.com'; $myvars = 'myvar1=' . $myvar1 .

How does post in PHP work?

The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING. The POST method does not have any restriction on data size to be sent. The POST method can be used to send ASCII as well as binary data.


1 Answers

CURL-less method with PHP5:

$url = 'http://server.com/path'; $data = array('key1' => 'value1', 'key2' => 'value2');  // use key 'http' even if you send the request to https://... $options = array(     'http' => array(         'header'  => "Content-type: application/x-www-form-urlencoded\r\n",         'method'  => 'POST',         'content' => http_build_query($data)     ) ); $context  = stream_context_create($options); $result = file_get_contents($url, false, $context); if ($result === FALSE) { /* Handle error */ }  var_dump($result); 

See the PHP manual for more information on the method and how to add headers, for example:

  • stream_context_create: http://php.net/manual/en/function.stream-context-create.php
like image 178
dbau Avatar answered Sep 24 '22 17:09

dbau