Post XML with HTTPS Authentication using PHP and cURL

Recently I needed to post XML to a particular API and this API required HTTPS authentication. So I needed to send a username / password with the request.

This was pretty straightforward in C#.NET ( at least from my foggy memory ). You needed to use NetworkCredentials. But it was a bit difficult to find a similar way of doing this in PHP… but eventually I found this gem.

This uses cURL which is just a library to send and receive data from remote sites. Now all I needed was a neat way of using cURL to post XML… and I found a neat implementation here.

Two plus two and you get …

$request_xml = "<?xml version='1.0' encoding='utf-8'?>
<request>
	<id>12345</id>
	<email>eoin@dolepaddy.com</email>
<request>";

//Initialize handle and set options
$username = 'dolepaddy';
$password = 'secret123';
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, 'https://connect.tosomeserver.com/xmlrpc'); 
curl_setopt($ch, CURLOPT_USERPWD, $username.':'.$password);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_TIMEOUT, 4); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $request_xml); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close'));

//Execute the request and also time the transaction ( optional )
$start = array_sum(explode(' ', microtime()));
$result = curl_exec($ch); 
$stop = array_sum(explode(' ', microtime()));
$totalTime = $stop - $start;

//Check for errors ( again optional )
if ( curl_errno($ch) ) {
	$result = 'ERROR -> ' . curl_errno($ch) . ': ' . curl_error($ch);
} else {
	$returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
	switch($returnCode){
		case 200:
			break;
		default:
			$result = 'HTTP ERROR -> ' . $returnCode;
			break;
	}
}

//Close the handle
curl_close($ch);

//Output the results and time
echo 'Total time for request: ' . $totalTime . "\n";
echo $result; 

2 thoughts on “Post XML with HTTPS Authentication using PHP and cURL

  1. Thank you… *sinks back in his chair crying*

    I wish I had found you 2 weeks ago…

    back when I hadn’t pulled 99% of my hair out…

    *cries some more*

    Thank you…

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s