How to Send a Post Request with PHP

  1. A. Using PHP Curl
  2. B. Using Pecl_Http
  3. C. Using the Object-Oriented (OO) Interface of Pecl_HTTP

In this tutorial, we aim share with you 3 competent ways of sending post requests using PHP.

Follow the examples below and choose the one that meets your needs better.

A. Using PHP Curl

The PHP cURL extension is a quite straightforward way allowing to combine different flags with setopt() calls.

Below is an example with an $xml variable that holds the XML prepared for sending:

$url = 'http://api.flickr.com/services/xmlrpc/';
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

As you can notice from the example above, first, the connection is initialised, and then some options are set with setopt(). These actions inform PHP about making a post request.

B. Using Pecl_Http

Generally, Pecl_Http combines two interfaces. The first one is considered procedural, the second one- object-oriented. Let’s start at discovering the first one. It provides you with a simpler way than the curl. Here is a script, which is translated for pecl_http:

$url = 'http://api.flickr.com/services/xmlrpc/';

$response = http_post_data($url, $xml);

C. Using the Object-Oriented (OO) Interface of Pecl_HTTP

As it was noted above, the second interface of xpecl_http is considered object- oriented. It is similar to the 2 extensions demonstrated above but applies a different interface. Here is how its code looks like:

$url = 'http://api.flickr.com/services/xmlrpc/';

$request = new HTTPRequest($url, HTTP_METH_POST);
$request->setRawPostData($xml);
$request->send();
$response = $request->getResponseBody();

You can notice that this code is longer than the previous one. You might think that it is more complicated, yet it is as powerful and flexible as the previous ones. So, it can be an outstanding option to implement in your practice.


Do you find this helpful?

Related articles