Fix SSL certificate problem with PHP curl

0
40582
Fix SSL certificate problem with PHP curl

In this article, I will show share with you a tip to fix SSL certificate problem with PHP curl when making HTTPS requests.

Making HTTPS requests

Before talking about the issue, let us try an old example by making HTTP request.

$url = "http://WEBSITE";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($ch);

if(curl_errno($ch)) {
    echo 'Error: '.curl_error($ch);
} else {
    echo $result;
}

curl_close ($ch);

It is alright for HTTP site, but if we change the $url into a HTTPS url, ex. https://petehouston.com , does it work normally?

No, it doesn’t. It shows this nagging error:

Error: SSL certificate problem: unable to get local issuer certificate

The error means we need to configure curl instance to deal with SSL-enabled websites.

Fix SSL certificate problem

There are two ways to fix SSL certificate problem with PHP curl module.

  1. Specify the valid CA certificate to curl client.
  2. Ignore SSL verification.

Solution 1: Use a valid CA certificate

I’m not going to explain what CA certificate is and why we need it to make requests.

You just need to download CA certificate provided by curl author, https://curl.haxx.se/docs/caextract.html, or click here to download.

Save the file somewhere in your computer, ex. ~/certs/cacert.pem if you’re on Linux or MacOS, D:\certs\cacert.pem if you’re using Windows.

Config the curl instance with CURLOPT_CAINFO to point to the cacert.pem file.

// for Linux/Mac
curl_setopt($ch, CURLOPT_CAINFO, '/home/petehouston/certs/cacert.pem');

// for Windows
curl_setopt($ch, CURLOPT_CAINFO, 'D:/certs/cacert.pem');

Try to execute the script again, it should work now!

You can also pre-configure the CA certificate by putting it into php.ini, so you don’t need to configure manually for each curl instance.

[curl]
; A default value for the CURLOPT_CAINFO option. This is required to be an
; absolute path.
curl.cainfo = "/home/petehouston/certs/cacert.pem"

Solution 2: Ignore SSL verification

If you don’t really care about SSL verification, you can ignore it by disable the CURLOPT_SSL_VERIFYPEER key.

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

It is just working as it with configured certificate.

Conclusion

So which one should I use, you ask?

Again, if you don’t care about the authenticity of the SSL then ignore it; otherwise, make sure you request to the right one.

That’s it! I’ve just shown you how to fix SSL certificate problem with PHP curl module.