Skip to content
Advertisement

file_get_contents(): Peer certificate did not match

I used PHP 5.5 but I forced to update it and now I’m using PHP 5.6.19.

Now, when I’m trying to communicate with external API I get warning:

Warning: file_get_contents(): Peer certificate CN=*.domain.com' did not match expected CN=api.domain.com’

It hasn’t appeared in previous PHP version.

    $encryptedEncodedData // this is json encoded
//array, then encrypted by mcrypt with rijndael-128 and finally bin2hex.

    $context = stream_context_create(array(
                        'http' => array(
                            'method' => 'POST',
                            'header' => 'Content-Type: application/json',
                            'content' => $encryptedEncodedData,
                        )
                    ));

    $api = 'https://api.domain.com/service';

    $response = file_get_contents($api, FALSE, $context);

I don’t know what is reason for this warning.


I decided to disable peer verfy until my admins will fix problem with cert and I changed $context following:

$context = stream_context_create(array(
                    'http' => array(
                        'method' => 'POST',
                        'header' => 'Content-Type: application/json',
                        'content' => $encryptedEncodedData,
                        'verify_peer'      => false,
                        'verify_peer_name' => false,
                        ), 
                    )
                );

But still not working. Did I do this correct? Getting same Warning.

Advertisement

Answer

There seems to be something wrong with the SSL certificate.

But the settings is changed in php 5.6 you can fix this by ignoring the verification, or when you have a self signed certificate allow_self_signed can be related.

 stream_context_create($ourStuff, ['verify_peer' => false]);

More information and settings: http://php.net/manual/en/context.ssl.php

Which is referred to from http://php.net/manual/en/function.stream-context-create.php

Note that disabling validation can be a security risk, and should be only done if you know what you are doing.

The default value of verify_peer has been changed to true in newer php versions (>= 5.6). Which means there was always a security risk.

As noted by deceze you should only do this when you are sure all other things are correctly like your own php configuration:

Step 1: test the remote certificate whether it’s valid using openssl CLI tool or whatever other methods you prefer. If remote cert is fine.

Step 2: figure out why PHP can’t accept it. If it’s because PHP has problems validating wildcard certs, see if there’s some fix for that. Or if it’s because PHP doesn’t have a local CA store, which is easy to fix.

Step 3: disable peer verification.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement