I’d like to make a curl call using basic auth in PHP, and parse the JSON it returns.
I put the url and basic auth info into Postman, and Postman gets the JSON back.
However, when I try to do it with PHP on my machine, I don’t get anything.
<?php
// Initializing curl
$curl = curl_init();
// Sending GET request to reqres.in
// server to get JSON data
curl_setopt($curl, CURLOPT_URL,
"https://UserName:Password@myurl.com/api/contacts/1");
// Telling curl to store JSON
// data in a variable instead
// of dumping on screen
curl_setopt($curl,
CURLOPT_RETURNTRANSFER, false);
// Executing curl
$response = curl_exec($curl);
// Checking if any error occurs
// during request or not
if($e = curl_error($curl)) {
echo $e;
} else {
// Decoding JSON data
$decodedData =
json_decode($response, true);
// Outputting JSON data in
// Decoded form
var_dump($decodedData);
}
// Closing curl
curl_close($curl);
?>
Although you’re correct, I wonder why the OP doesn’t get all the response displayed in the browser screen with their current settings. Doesn’t really tally with “I don’t get anything”.
Strictly speaking, the URL format is correct to RFC1738 standards for HTTP traffic. Whether the CURL parser translates it into the appropriate header or not is another question.
With the code below, I don’t get anything back at all… ```<?php
// Initializing curl
$curl = curl_init();
// Sending GET request to reqres.in
// server to get JSON data
curl_setopt($curl, CURLOPT_URL,“myurl.com/api/endpoint”);
curl_setopt($curl, CURLOPT_USERPWD, “myusername:mypassword”);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// Telling curl to store JSON
// data in a variable instead
// of dumping on screen
curl_setopt($curl,
CURLOPT_RETURNTRANSFER, true);
// Checking if any error occurs
// during request or not
if($e = curl_error($curl)) {
echo $e;
} else {
var_dump($response);
// Decoding JSON data
$decodedData =
json_decode($response, true);
// Outputting JSON data in
// Decoded form
var_dump($decodedData);
That’s because you call curl_exec() and assign the response to $response, then your next line is a return which terminates execution before you try to echo $response.