I have been doing a lot of work using REST API's in PHP but I hit a wall when I needed to send a request from PHP that sent my POST data. So how do you do it?


I stumbled across a variety of methods that I will discuss in more detail below. PHP has a cURL extension which allows this, additionally there is pecl_http the PECL extension but there are a few other methods of doing it.

Sending POST from cURL

Most PHP releases now come with cURL enabled my default (if it isn't, ask your host) which allows you to create a connection and send the request. It comes with a large variety of options that you can set, I will run through the ones we require.

# Our new data
$data = array(
    'election' => 1,
    'name' => 'Test'
# Create a connection
$url = '/api/update';
$ch = curl_init($url);
# Form data string
$postString = http_build_query($data, '', '&');
# Setting our options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
# Get the response
$response = curl_exec($ch);

That's all the basics too it.  The CURLOPT_RETURNTRANSFER flag tells cURL to pass the return value to curl_exec instead of outputting it, the response is stored in $response. There is a wide selection of configuration options and parameters available for cURL:

Sending POST from PECL

When using the same data as formed above, we can use:

# Get the URL
$url = '/api/update';
# Get response
$response = http_post_data($url, $postString);

This extension has a method to post a request and it can optionally accept data to go with it. Overall it is very simple to use, more examples can be found:

Additionally, you may want to alternate the method you use based on whether or not PECL is active, you can check using: (Source, php + http_post_data - Stack Overflow)

if extension_loaded('pecl_http') == false) {
    # Extension is not installed
# You can also check..
if(function_exists('http_post_data') == false) {
    # Function not available

Sending POST from PECL - OO Approach

We can also use the HTTPRequest class (using the same data in example 1):

$url = '/api/update';
# Create the request, state method = HTTP_METH_POST
$request = new HTTPRequest($url, HTTP_METH_POST);
# Send our request
# Get the response
$response = $request->getResponseBody();

The extension is very flexible and powerful, it is worth reading through the documentation for all available methods:

Sending POST using HTTP Context

This method uses the stream HTTP context, an example is:

# Form our options
$opts = array('http' =>
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postString
# Create the context
$context = stream_context_create($opts);
# Get the response (you can use this for GET)
$result = file_get_contents('/api/update', false, $context);

Sending POST using TCP stream

An example using a socket to write the request to the stream and reading the response can be found on Guru - Multiplexing

Have you used any of the methods above? What are your opinion on them? Let me know by mentioning #ALJTMedia on Twitter or leave a comment on our Facebook or Google+ page.

Other Resources

Ignite your brand, utilise user-generated content no matter where you or your audience are ›