Fetching json data from password protected url using php and curl



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.


If you simply try to access a 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.

Real time example and solution


When fetching json data from password protected url using php and curl, I had faced a problem.


The problem i got is

"error:14077458:SSL routines:SSL23_GET_SERVER_HELLO:reason(1112) "

I searched many websites for the solution to this particular problem. After 2 hours of a long research, i found one working solution.

Solution:

"The problem has been solved.  When using curl CURLOPT_SSLVERSION must be set to 3."



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);

}

I just wanted to share the problem and how i solved it. May be you will solve the problem when you faced this problem without spending a lots of hours.

Cheers!

Comments

Post a Comment

Popular Posts