Three Ways to Make a POST Request from PHP
Monday, January 18. 2010
Nice post. :) There’s also using the streams HTTP context – see Example #1 here: http://php.net/manual/en/context.http.php – as well as opening a TCP stream and manually writing the HTTP request to it. PEAR::HTTP_Client and Zend_Http_Client from Zend Framework are other client library options as well.
Take a look at http://netevil.org/blog/2005/may/guru-multiplexing
Good article! I prefer curl personally. You made a typo in the curl code example. In the third line with curl_setopt you use the variable $curl which should be $ch like the others :)
Actually, there is a clean third way using built-in methods:
$params = array(‘http’=>array(‘method’=>‘post’,‘content’=>http_build_query($postArr)));
$context= stream_context_create($params);
$stream= fopen($url, ‘rb’, false, $context);
Here’s another variant on the same approach, setting a header for XML data and using file_get_contents() instead of fopen() (but the same fopen wrappers are used).
$context = stream_context_create(array(
‘http’ => array(
‘method’ => ‘POST’,
‘header’ => ‘Content-Type: application/xml’,
‘content’ => $xml
)
));
$result = file_get_contents($url, false, $context);
Right, PHP supports http natively as well, and is very easy to implement.
cURL and pecl’s http however help to process complex requests. Additionnaly cURL supports all kind of protocols, including sftp/ssh2/ftps :)
There’s also a few PEAR packages that you can use: HTTP_Request and HTTP_Client.
I also prefer the stream_context_create method it is simple, native and will do for most POST requests.
The title of this post should read: Three Ways to Make a POST Request from PHP (using extensions instead of built-in coolness)
BTW php supports all kinds of protocols [1] too. Streams [2] FTW!
[1] http://php.net/wrappers
[2] http://php.net/streams
Not sure if this adds anything over the other commenters posts, but I’m posting it anyway :-)
http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
Goodness, what a lot of comments! Thanks everyone for taking the time to comment, what excellent and useful contributions!! I definitely learned a few tricks from my readers today :)
One other advantage of cURL and pecl_http (which is built on libcurl, the same library as the cURL extension uses) is that they support parallel requests, which can be a significant performance boost if you need to execute multiple requests from a single process. Look at the curl_multi_* functions in cURL and HttpRequestPool in pecl_http.
yeh, as noticed by first comment you forget to see in PEAR. It is pretty simple to use php based library because it will be supported even curl or pecl libraries are unavailable.


