Fetching JSON data from password-protected URL using PHP and curl

Fetching JSON data from password-protected URL using PHP

From PHP, you can access the useful cURL Library to make requests to URLs using a variety of protocols such as HTTP, HTTPS, FTP, LDAP etc.

Fetching JSON data from password-protected URL using PHP

If you simply try to access an HTTPS (SSL or TLS-protected resource) in PHP using cURL, you’re likely to run into some difficulty. The problem is that cURL has not been configured to trust the server’s HTTPS certificate.

Following is the source code that I used and it worked like a charm.

function fetch_json_url(){



   $url = 'https:/example.com/testjson';

   $username = 'your username';

   $password = 'your password';





// Initialize session and set URL.

$ch = curl_init();



// Set URL to download

curl_setopt($ch, CURLOPT_URL, $url);



// Include header in result? (0 = yes, 1 = no)

curl_setopt($ch, CURLOPT_HEADER, 0);



//Set content Type

curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-type: application/json'));



// Should cURL return or print out the data? (true = return, false = print)

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);



curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");



//to blindly accept any server certificate, without doing any verification //optional

   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);



//The most important is

   curl_setopt($ch, CURLOPT_SSLVERSION, 3);





// Download the given URL, and return output

    $result = curl_exec($ch);



// Close the cURL resource, and free system resources

   curl_close($ch);



   $data = json_decode($result, true);



    print_r($data);

}

Check This Also

Difference between AngularJS and Angular 2 Make a Mobile app in just 10 minutes With Ionic Framework Angular 9: What to Expect in New Version of Angular Alert (Toaster) Notifications in Angular 8