reCaptcha file_get_contents(): SSL 操作失败

reCaptcha file_get_contents(): SSL operation failed

我正在为我的网页使用 Google reCaptcha。

在测试模式下一切正常。无 SSL。

当我在生产环境中测试我的网页时,出现以下错误:

Warning: file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in /vendor/google/recaptcha/src/ReCaptcha/RequestMethod/Post.php on line 68

Warning: file_get_contents(): Failed to enable crypto in /vendor/google/recaptcha/src/ReCaptcha/RequestMethod/Post.php on line 68

Warning: file_get_contents(https://www.google.com/recaptcha/api/siteverify): failed to open stream: operation failed in /vendor/google/recaptcha/src/ReCaptcha/RequestMethod/Post.php on line 68
["invalid-json"]

我这样调用 reCaptcha API:

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
                async defer></script>

如 google 的开发者页面所述。

我在 hoststar.ch 托管我的网页。有 TSL 1.2 运行.

我希望有人能帮助我。

为了回应您最后的评论,我知道您无法更改 Google 的 reCaptcha api - 我的意思只是在 example.com 上实际执行 file_get_contents(它确实存在)作为测试,看看您是否可以使用该方法检索任何内容,因为某些网络主机禁用相关功能。

但是,对于 Google reCatcha API,您可能需要为 file_get_contents 函数调用指定额外的参数,特别是设置 context 选项专门用于SSL.

$secret = 'Your google secret';
$captcha = trim( $_POST['g-recaptcha-response'] );
$ip = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$captcha}&remoteip={$ip}";

$options=array(
    'ssl'=>array(
        'cafile'            => '/path/to/cacert.pem',
        'verify_peer'       => true,
        'verify_peer_name'  => true,
    ),
);
$context = stream_context_create( $options );
$res=json_decode( file_get_contents( $url, FILE_TEXT, $context ) );
if( $res->success ){/* all good */}
else{ /* captcha failed */ }

如果您还没有 cacert.pem or ca-bundle.crt 的副本,您可以从它们各自的链接下载它们。 cafile 的路径可以使用 - 将副本保存到您的主机并更正路径以适合您的环境。

file_get_contents 更改为 curl。这是代码,

变化-

$verify=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
 $captcha_success=json_decode($verify);  /*store json response*/

到此代码:

$ch = curl_init("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$verify = curl_exec($ch);

$captcha_success=json_decode($verify);  /*store json response*/

请注意$secret是存储在服务器端的密钥,$response是通过[=29=发送的recaptcha响应] 来自前端。