Skip to content

Instantly share code, notes, and snippets.

@roberto-butti
Last active February 22, 2016 10:40
Show Gist options
  • Save roberto-butti/07a527df99fe4cc23ffe to your computer and use it in GitHub Desktop.
Save roberto-butti/07a527df99fe4cc23ffe to your computer and use it in GitHub Desktop.
Send a JSON in a POST, with HTTP Basic Auth
<?php
$endpoint_url="your_url_here";
$string_json = "your_json_string";
$username="username";
$password ="password";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $string_json );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$start = array_sum(explode(' ', microtime()));
$output = curl_exec($ch);
$stop = array_sum(explode(' ', microtime()));
$totalTime = $stop - $start;
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;
}
}
echo 'Total time for request: ' . $totalTime . "\n";
echo $result;
$info = curl_getinfo($ch);
var_dump($output);
echo "<pre>";
var_dump($info);
echo "</pre>";
curl_close($ch);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment