file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

前端 未结 16 1933
情歌与酒
情歌与酒 2020-11-22 04:31

I’ve been trying to access this particular REST service from a PHP page I’ve created on our server. I narrowed the problem down to these two lines. So my PHP page looks li

16条回答
  •  甜味超标
    2020-11-22 04:42

    Had the same error with PHP 7 on XAMPP and OSX.

    The above mentioned answer in https://stackoverflow.com/ is good, but it did not completely solve the problem for me. I had to provide the complete certificate chain to make file_get_contents() work again. That's how I did it:

    Get root / intermediate certificate

    First of all I had to figure out what's the root and the intermediate certificate.

    The most convenient way is maybe an online cert-tool like the ssl-shopper

    There I found three certificates, one server-certificate and two chain-certificates (one is the root, the other one apparantly the intermediate).

    All I need to do is just search the internet for both of them. In my case, this is the root:

    thawte DV SSL SHA256 CA

    And it leads to his url thawte.com. So I just put this cert into a textfile and did the same for the intermediate. Done.

    Get the host certificate

    Next thing I had to to is to download my server cert. On Linux or OS X it can be done with openssl:

    openssl s_client -showcerts -connect whatsyoururl.de:443 /dev/null|openssl x509 -outform PEM > /tmp/whatsyoururl.de.cert
    

    Now bring them all together

    Now just merge all of them into one file. (Maybe it's good to just put them into one folder, I just merged them into one file). You can do it like this:

    cat /tmp/thawteRoot.crt > /tmp/chain.crt
    cat /tmp/thawteIntermediate.crt >> /tmp/chain.crt
    cat /tmp/tmp/whatsyoururl.de.cert >> /tmp/chain.crt
    

    tell PHP where to find the chain

    There is this handy function openssl_get_cert_locations() that'll tell you, where PHP is looking for cert files. And there is this parameter, that will tell file_get_contents() where to look for cert files. Maybe both ways will work. I preferred the parameter way. (Compared to the solution mentioned above).

    So this is now my PHP-Code

    $arrContextOptions=array(
        "ssl"=>array(
            "cafile" => "/Applications/XAMPP/xamppfiles/share/openssl/certs/chain.pem",
            "verify_peer"=> true,
            "verify_peer_name"=> true,
        ),
    );
    
    $response = file_get_contents($myHttpsURL, 0, stream_context_create($arrContextOptions));
    

    That's all. file_get_contents() is working again. Without CURL and hopefully without security flaws.

提交回复
热议问题