PHP cURL调用Google reCaptcha无响应,返回值为Null
解决PHP cURL调用Google reCaptcha返回Null的问题
你的问题出在Google reCaptcha的siteverify接口不接受JSON格式的POST数据,它要求使用application/x-www-form-urlencoded(普通表单提交)格式传递参数,而你代码里用了json_encode($data),导致接口无法识别参数,返回空响应。
直接修改代码里的POST数据部分即可解决:
// set API URL $url = 'https://www.google.com/recaptcha/api/siteverify'; // Collection object $data = [ 'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', // 你的reCaptcha密钥 'response' => $_POST['recaptcha'] ]; // Initializes a new cURL session $curl = curl_init($url); // Set the CURLOPT_RETURNTRANSFER option to true curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Set the CURLOPT_POST option to true for POST request curl_setopt($curl, CURLOPT_POST, true); // 改用http_build_query生成表单格式的参数,替换json_encode curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // 可选:添加SSL相关设置(避免部分环境SSL验证失败) curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // Execute cURL request with all previous settings $response = curl_exec($curl); // 添加错误排查代码,方便后续调试 if($response === false) { echo 'cURL错误信息:' . curl_error($curl) . PHP_EOL; } // Close cURL session curl_close($curl); echo 'the response was ' . $response . PHP_EOL;
另外,之后再遇到类似cURL无响应的情况,一定要加上curl_error的判断,能直接定位到问题(比如SSL验证失败、网络不通等)。
内容的提问来源于stack exchange,提问作者Peneh
相关产品推荐
相关产品推荐

