Last active
February 22, 2016 10:40
-
-
Save roberto-butti/07a527df99fe4cc23ffe to your computer and use it in GitHub Desktop.
Send a JSON in a POST, with HTTP Basic Auth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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