martincarlin87
martincarlin87

Reputation: 11042

Fetching json data from password protected url using php and curl

I am trying to fetch a json string from a password protected url.

I think my code should work but when I open my script in the browser I just have a blank page.

Here's my code:

<?php
error_reporting(E_ALL);

$url = 'https://api.domain.com?api=latest&format=json';

$username = 'username';
$password = 'password';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//curl_setopt($ch, CURLOPT_REFERER, $url);

$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

$data = json_decode($result, true);

print_r($data);

?>

Any help would be much appreciated.

Upvotes: 2

Views: 3457

Answers (1)

Alex
Alex

Reputation: 12039

Try adding this

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, 1);

Upvotes: 1

Related Questions