tags:

views:

3754

answers:

4

I've seen numerous methods of POSTing data with PHP over the years, but I'm curious what the suggested method is, assuming there is one. Or perhaps there is a somewhat unspoken yet semi-universally-accepted method of doing so. This would include handling the response as well.

A: 

cURL is the only reliable way I know of, to POST data, aside from using a socket.

Now if you wanted to send data via GET there are several methods:
cURL
sockets
file_get_contents
file
and others

Unkwntech
+1  A: 

You could try the Snoopy script
It is useful on hosting providers that don't allow fopen wrappers
I have used it for several years to grab RSS feeds.

tyndall
Wow. I just looked at the Snoopy Script and it is brilliantly-simple. I'll definitely check this out.
Jonathan Sampson
I think it is even included in some larger open source PHP projects.
tyndall
The Zend_Http_Client is also a good idea. I would use that if you are going to be using other parts of the Zend Framework.
tyndall
@Bruno, I am not currently using Zend, nor do I plan to in the future. I do plan on using CodeIgniter though, so I will likely search in that community for potential solutions too.
Jonathan Sampson
Then I would lean towards Snoopy, and write a small abstraction or service layer for what you need it for. That way your code relies on your service layer not Snoopy. You'll be able to swap it out later.
tyndall
A: 

There isn't really a standard way. In code meant for distribution, I generally check cURL, file_get_contents and sockets, using the first one found. Each of those supports GET and POST, and each of those may or may not be available (or work) depending on the PHP version and configuration.

Basically something like:

function do_post($url, $data) {
  if (function_exists('curl_init') && ($curl = curl_init($url))) {
    return do_curl_post($curl, $data);
  } else if (function_exists('file_get_contents') && ini_get('allow_url_fopen') == "1") {
    return do_file_get_contents_post($url, $data);
  } else {
    return do_socket_post($url, $data);
  }
}
waqas
+1  A: 

I like Zend_Http_Client from Zend Framework.

It basically works using stream_context_create() and stream_socket_client().

Small example:

$client = new Zend_Http_Client();
$client->setUri('http://example.org');
$client->setParameterPost('foo', 'bar')
$response = $client->request('POST');

$status = $response->getStatus();
$body = $response->getBody();
Karsten