How to use PHP curl GET and POST with JSON web services

Here are two PHP scripts I just wrote that use curl and curl_setopt. The first example makes a GET request, and the second example makes a POST request, and passes JSON data to the web service it accesses.

A PHP curl GET request

This first one makes an HTTP GET request and prints the data that is returned by the URL that it hits:


# An HTTP GET request example

$url = 'http://localhost:8080/stocks';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
echo $data;


A PHP curl POST request, with JSON data

This next one makes an HTTP POST request. The way it works is that it sits in the middle of (a) a Sencha ExtJS client and (b) another web service at the URL shown. The Sencha client gives this script the data in a simple POST format, and this script converts that data to JSON, passes it to the URL shown, and returns whatever information that service returns directly to the Sencha client:


# An HTTP POST request example

# a pass-thru script to call my Play server-side code.
# currently needed in my dev environment because Apache and Play run on
# different ports. (i need to do something like a reverse-proxy from
# Apache to Play.)

# the POST data we receive from Sencha (which is not JSON)
$id = $_POST['id'];
$symbol = $_POST['symbol'];
$companyName = $_POST['companyName'];

# data needs to be POSTed to the Play url as JSON.
# (some code from
$data = array("id" => "$id", "symbol" => "$symbol", "companyName" => "$companyName");
$data_string = json_encode($data);

$ch = curl_init('http://localhost:8080/stocks/add');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

//execute post
$result = curl_exec($ch);

//close connection

echo $result;


In summary, if you needed some PHP curl examples, including how to set curl options with curl_setopt, I hope these examples have been helpful.