Using CURL

Suppose you want to pass information to a remote script, have that remote script process the data passed to it and pass some different data back. We can do all this with just one file on each site by using CURL to post the required data to the remote script and using JSON to return the results.

To be able to pass information to the remote script we need three things. First we need the URL of the remote script that we are calling, second we need an array containing all of the fields that we want to pass to that remote script, and finally we need the CURL commands to perform the processing.

To pass all of the fields from one script to the other we can define a simple PHP associative array that contains all of the fields to be passed. For example:

$fields = array(
'field_one' => 'x',
'field_two' => 'y',
'field_three' => 'z'

The values to be passed need to be serialised in order for CURL to post them to the other script and this is most easily done by using a function that also sends the data and receives the result. The following function will handle this just as long as you don't need the remote script to retain data in a session cookie between calls:

function sendData($url, $fields) {
foreach($fields as $key=>$value) { $fields_string .= $key.'='.urlencode($value).'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = json_decode(curl_exec($ch),true);
return $result;

Simply set $url to the address of the remote script, load the variables to be passed to the remote script into $fields and then call sendData() and the remote script will be run and if a valid JSON encoded value is echoed back then that will be converted into an array and returned. If a valid JSON encoded value is not returned then the result will be NULL.

Within the script being called the values passed to it will be available to the script via the $_POST[] array. That remote script can then process those values in whatever way you require and create a new $fields array of the values to be passed back. That array then simply needs to be echoed in JSON format in order to pass all the values back to the calling script.

echo json_encode($fields);

Once the values are returned the original script will continue running from the statement following the sendData() call.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow