Url error 60 ssl certificate problem self signed certificate

I try to send curl request with my correct APP_ID, APP_SECRET etc. to the https://oauth.vk.com/access_token?client_id=APP_ID&client_secret=APP_SECRET&code=

I try to send curl request with my correct APP_ID, APP_SECRET etc. to the

  https://oauth.vk.com/access_token?client_id=APP_ID&client_secret=APP_SECRET&code=7a6fa4dff77a228eeda56603b8f53806c883f011c40b72630bb50df056f6479e52a&redirect_uri=REDIRECT_URI 

I need to get access_token from it, but get a FALSE and curl_error() print next message otherwise:

60: SSL certificate problem: self signed certificate in certificate chain

My code is:

    // create curl resource
    $ch = curl_init();

    // set url
    curl_setopt($ch, CURLOPT_URL, $url);
    //return the transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // $output contains the output string
    $output = curl_exec($ch);
    if ( ! $output) {
        print curl_errno($ch) .': '. curl_error($ch);
    }

    // close curl resource to free up system resources
    curl_close($ch);

    return $output;

When I move manually to the link above, I get access_token well. Why it doesn’t work with curl? Help, please.

James MV's user avatar

James MV

8,46916 gold badges63 silver badges94 bronze badges

asked Jan 17, 2014 at 14:15

Victor Bocharsky's user avatar

Victor BocharskyVictor Bocharsky

11.6k13 gold badges57 silver badges88 bronze badges

3

Answers suggesting to disable CURLOPT_SSL_VERIFYPEER should not be accepted. The question is «Why doesn’t it work with cURL», and as correctly pointed out by Martijn Hols, it is dangerous.

The error is probably caused by not having an up-to-date bundle of CA root certificates. This is typically a text file with a bunch of cryptographic signatures that curl uses to verify a host’s SSL certificate.

You need to make sure that your installation of PHP has one of these files, and that it’s up to date (otherwise download one here: http://curl.haxx.se/docs/caextract.html).

Then set in php.ini:

curl.cainfo = <absolute_path_to> cacert.pem

If you are setting it at runtime, use (where $ch = curl_init();):

curl_setopt ($ch, CURLOPT_CAINFO, dirname(__FILE__)."/cacert.pem");

answered May 10, 2014 at 19:40

erlangsec's user avatar

14

This workaround is dangerous and not recommended:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

It’s not a good idea to disable SSL peer verification. Doing so might expose your requests to MITM attackers.

In fact, you just need an up-to-date CA root certificate bundle. Installing an updated one is as easy as:

  1. Downloading up-to-date cacert.pem file from cURL website and

  2. Setting a path to it in your php.ini file, e.g. on Windows:

    curl.cainfo=c:phpcacert.pem

That’s it!

Stay safe and secure.

Community's user avatar

answered Sep 27, 2015 at 20:39

zxcmehran's user avatar

zxcmehranzxcmehran

1,37513 silver badges24 bronze badges

10

If the SSL certificates are not properly installed in your system, you may get this error:

cURL error 60: SSL certificate problem: unable to get local issuer
certificate.

You can solve this issue as follows:

Download a file with the updated list of certificates from https://curl.haxx.se/ca/cacert.pem

Move the downloaded cacert.pem file to some safe location in your system

Update your php.ini file and configure the path to that file:

VPK's user avatar

VPK

3,0121 gold badge27 silver badges35 bronze badges

answered Sep 29, 2017 at 6:59

sunil's user avatar

sunilsunil

391 bronze badge

1

Important: This issue drove me crazy for a couple days and I couldn’t figure out what was going on with my curl & openssl installations. I finally figured out that it was my intermediate certificate (in my case, GoDaddy) which was out of date. I went back to my godaddy SSL admin panel, downloaded the new intermediate certificate, and the issue disappeared.

I’m sure this is the issue for some of you.

Apparently, GoDaddy had changed their intermediate certificate at some point, due to scurity issues, as they now display this warning:

«Please be sure to use the new SHA-2 intermediate certificates included in your downloaded bundle.»

Hope this helps some of you, because I was going nuts and this cleaned up the issue on ALL my servers.

peterh's user avatar

peterh

11.4k17 gold badges85 silver badges104 bronze badges

answered Nov 13, 2014 at 7:25

Lee's user avatar

2

To add a more specific answer, I ran into this when using Guzzle v7, the PHP HTTP request package. Guzzle allows you to bypass this like so:

use GuzzleHttpClient;

$this->client = new Client([
    'verify' => false,
]);

Original source comment: https://github.com/guzzle/guzzle/issues/1490#issuecomment-375667460

answered Feb 4, 2022 at 20:11

Aaron Krauss's user avatar

Aaron KraussAaron Krauss

7,2261 gold badge14 silver badges19 bronze badges

Error: SSL certificate problem: self signed certificate in certificate
chain

Solution:
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);    
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

answered May 19, 2020 at 4:35

Sundar's user avatar

SundarSundar

2432 silver badges5 bronze badges

1

‘cURL error 60 SSL certificate problem’ occurs when we make a cURL call to third party services.

Here at Bobcares, we have seen several such cURL command related errors as part of our Server Management Services for web hosts and online service providers.

Today we’ll take a look at the causes for this error and see the fix.

What causes ‘cURL error 60 SSL certificate problem’ error to occur

Digital certificates are mainly used in transferring sensitive content. These digital certificates are issued by certificate authorities or CA.

When a cURL receives a server CA that is not signed by one of the trusted certificates in the installed CA certificate store, then it will lead to an error: “failed to verify the legitimacy of the server” during the SSL handshake. As a result, SSL will then refuse the communication with the server leading to an SSL error.

In short, this error occurs because cURL makes sure to verify and make a secure connection request using a self-signed certificate. But when it doesn’t find any valid certificate then it throws this error message.

How we fix the error ‘cURL error 60 SSL certificate problem’

Now let’s see how our Support Engineers resolve this error message.

1. Re-download the cURL CA-Bundle from the cURL site to fix this error. Here are the steps for it.

  • First, download the “cacert.pem” from the link: http://curl.haxx.se/docs/caextract.html
  • Next copy the complete page and save it as “cacert.pem
  • Now, open the php.ini file and add the following line in it.
    curl.cainfo = “[pathtofile]cacert.pem”
    In, case, if the php.ini file doesn’t have the curl.cainfo line, then just add it to the end of the file. Then add the file path where cacert.pem file is saved.
  • Finally, restart the web server or on Windows, restart the application pool and try the request again.

2. If the insecure certificate is a self-signed, known-trusted certificate, then load the certificate to your local trusted certificate location for your OS.

[Need any further assistance in fixing curl errors? – We are here to help you.]

Conclusion

In short, this error occurs when cURL doesn’t find any valid certificate to communicate over https. Today, we saw how our Support Engineers fix this error.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

C 30 сентября 2021 года на сайтах WordPress, для которых был установлен сертификат Let’s Encrypt, могут перестать работать HTTP API запросы.

Например такой запрос будет выдавать ошибку:

$res = wp_remote_get( 'https://wp-kama.ru/' );

if( is_wp_error( $res ) ){
	echo $res->get_error_message();
}

Получим:

cURL error 60: SSL certificate problem: certificate has expired

Такую ошибку можно будет увидеть где угодно, например:

  • в админке при проверке обновлений WordPress
  • при проверке обновлений плагинов
  • при обращении к апи любого сервиса. Например, перестанет работать плагин TinyPNG — JPEG, PNG & WebP image compression и куча других, которые используют какие бы то ни было запросы.

Почему мы видим ошибку certificate has expired?

Почему так происходит подробно расписано на хабре.

Если коротко, то в ядре WP есть файл корневых сертификатов /wp-includes/certificates/ca-bundle.crt который используется для проверки SSL всех запросов созданных через HTTP API. В этом файле просрочен один из корневых сертификатов на основе которого был создан сертификат для вашего сайта. Поэтому запрос не может пройти проверку и выдается такая ошибка.

С очередными обновлениями WP эта ошибка должна пропасть, но вот что делать если решение нужно уже сегодня, или если вы не планируете обновлять WordPress, а рабочие HTTP запросы нужны.

Решение ошибки: cURL error 60: SSL certificate has expired

Вариант 1

Нужно обновить контент файла /wp-includes/certificates/ca-bundle.crt изменить его на контент этого файла https://curl.haxx.se/ca/cacert.pem.

Изменять в данном случае файл ядра допустимо, потому что при следующем обновлении WP проблема исчезнет. См. соответствующий коммит на GitHub.

Это можно сделать вручную:

  1. Скачайте файл по ссылке https://curl.haxx.se/ca/cacert.pem.
  2. Обновите контент /wp-includes/certificates/ca-bundle.crt контентом из скаченного файла.

Или используйте следующий код

Использовать код удобно, когда у вас есть возможность запустить код из админки или как-то еще, например через плагин Code Snippets.

Добавьте следующий код куда угодно и перейдите на страницу http://ВАШСАЙТ.com/?update-wp-ca-bundle.

/**
 * Goto http://yoursite.com/?update-wp-ca-bundle
 */
if( isset( $_GET['update-wp-ca-bundle'] ) ){

	$crt_file = ABSPATH . WPINC . '/certificates/ca-bundle.crt';
	$new_crt_url = 'https://curl.haxx.se/ca/cacert.pem';

	if( is_writable( $crt_file ) ){
		$new_str = file_get_contents( $new_crt_url );

		if( $new_str && strpos( $new_str, 'Bundle of CA Root Certificates' ) ){
			$up = file_put_contents( $crt_file, $new_str );

			echo $up ? 'OK: ca-bundle.crt updated' : 'ERROR: can`t put data to ca-bundle.crt';
		}
		else {
			echo 'ERROR: cant download https://curl.haxx.se/ca/cacert.pem';
		}
	}
	else {
		echo 'ERROR: ca-bundle.crt not writable';
	}

	exit;
}

После использования, код нужно удалить.

Вариант 2

Решить проблему можно через хук http_request_args. Этот хук нужно использовать в MU плагине.

  1. Создайте файл loader.php в папке wp-content/mu-plugins (если такой папки у вас нет, создайте её).

  2. Добавьте следующий код в этот файл:

    <?php
    
    require_once __DIR__ .'/fix-wp-ca-bundle/main.php';
  3. Создайте папку wp-content/mu-plugins/fix-wp-ca-bundle.

  4. Создайте файлы: main.php и ca-bundle.crt в папке fix-wp-ca-bundle.

    Добавьте следующий код в эти файлы.

    Код файла main.php:

    <?php
    
    defined( 'ABSPATH' ) || exit;
    
    /**
     * Update the path to the WordPress trusted root certificates.
     *
     * Actual certificates can be downloaded at this link: http://curl.haxx.se/ca/cacert.pem
     */
    add_filter( 'http_request_args', 'http_request_change_sslsertificates' );
    
    function http_request_change_sslsertificates( $parsed_args ){
    
    	$parsed_args[ 'sslcertificates' ] = __DIR__ . '/ca-bundle.crt';
    
    	return $parsed_args;
    }

    Контент файла ca-bundle.crt:

    Скопируйте контент этого файла http://curl.haxx.se/ca/cacert.pem

Должна получится такая структура:

Готово! Теперь все должно работать как и прежде.

Home » cURL error 60: SSL certificate problem: unable to get local issuer certificate

Last updated on June 17, 2022 by

Often, cURL error 60: SSL certificate problem: unable to get local issuer certificate error occurs when we try to call the API with the secure https:// protocol in the request URL. In this article, we will discuss why does this error occur? how to resolve: unable to get local issuer certificate error occurs? Let’s jump into it.

Why Does This Error Occur?

Just go to your API call code and try to run the request URL with only http:// protocol. You can’t see the error anymore because secure API calls require an SSL certificate.

This error occurs because the API call makes a secure connection request using the self-signed certificate. When it does not find a valid certificate, it throws an error.

It has a very very simple solution. We just need to download the certificate and set the path. Are you ready? Then let’s set up an SSL certificate step by step as below:

How To Resolve: unable to get local issuer certificate error?

  1. Download the “cacert.pem” free certificate file from the official website here: http://curl.haxx.se/docs/caextract.html
  2. Move the cacert.pem file in a reachable destination for the PHP. It is advisable to move the file for the WAMP user to C:wamp64binphpcacert.pem, for XAMPP user to C:xamppphpextrassslcacert.pem, for the AMPPS user to C:Program Files (x86)Amppsphpextrassslcacert.pem
  3. Now, open your php.ini file and find the “curl.cainfo” option. You will see something like the following:
  1. After that, we need to add the path of the certificate to “curl.cainfo” and remove semicolon(;) as follow:
curl.cainfo = "C:wamp64binphpcacert.pem"
  1. The very very most important step is to save and close your php.ini. Restart your web server and try your request again. If you do not set the right path, then you will experience a CURL 77 error.

Hurray! we have completed all steps to solve unable to get local issuer certificate error.

Additionally, read our guide:

  1. Specified Key Was Too Long Error In Laravel
  2. Run PHP Artisan Commands On Shared Hosting Servers
  3. How To Calculate Age From Birthdate
  4. Active Directory Using LDAP in PHP or Laravel
  5. How To Use The Laravel Soft Delete
  6. How To Add Laravel Next Prev Pagination
  7. Best Way to Remove Public from URL in Laravel
  8. Difference Between Factory And Seeders In Laravel
  9. Difference Between Events and Observers In Laravel
  10. Session Not Working In Laravel
  11. How To Install Vue In Laravel 8 Step By Step
  12. How To Handle Failed Jobs In Laravel
  13. Best Ways To Define Global Variable In Laravel
  14. How To Get Latest Records In Laravel
  15. Laravel Twilio Send SMS Tutorial With Example
  16. How To Pass Laravel URL Parameter
  17. Laravel 9 Resource Controller And Route With Example
  18. Laravel 9 File Upload Tutorial With Example
  19. How To Schedule Tasks In Laravel With Example
  20. Laravel Collection Push() And Put() With Example

That’s it from our end. We hope this article helped you to resolve cURL error 60: SSL certificate problem: unable to get local issuer certificate error.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post. 🙂 Keep Smiling! Happy Coding!

Понравилась статья? Поделить с друзьями:
  • Urban vpn ошибка установки
  • Urban vpn setup ended prematurely because of an error
  • Urban vpn connection error
  • Uptool error 0074
  • Uptool error 0071