从reCAPTCHA v1升级到v2——PHP服务端改造技术咨询
Got it, let's walk through upgrading your reCAPTCHA v1 implementation to v2 step by step—this is a common switch, so I’ll break it down clearly for your PHP backend:
- First, replace your old v1 keys with v2 ones. Head to the reCAPTCHA admin console (same place you got your v1 keys) and create a new v2 "I'm not a robot" checkbox site. You’ll get two keys:
- Site Key: For use in your frontend HTML
- Secret Key: Keep this locked away on your server—never expose it publicly
recaptchalib.php - You won’t need the v1 library anymore. Delete the
require_once('inc/func/recaptchalib.php');line entirely—v2 uses a direct API call instead of a local library.
Here’s the replacement code for your existing backend check, tailored to v2’s API:
First, define your secret key:
$secretKey = "YOUR_V2_SECRET_KEY"; // Swap this with your actual secret key
Then, handle the reCAPTCHA response (note: v2 uses g-recaptcha-response instead of v1’s recaptcha_response_field):
$resp = null; $error = null; // Check if the reCAPTCHA response was submitted if (isset($_POST['g-recaptcha-response'])) { // Prepare data to send to Google's verification endpoint $verificationData = [ 'secret' => $secretKey, 'response' => $_POST['g-recaptcha-response'], 'remoteip' => $_SERVER['REMOTE_ADDR'] // Optional but adds extra security ]; // Use cURL to send the verification request (preferred over file_get_contents) $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify'); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($verificationData)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); // Keep this enabled to avoid MITM attacks // Execute the request and parse the JSON response $apiResponse = curl_exec($curl); curl_close($curl); $verificationResult = json_decode($apiResponse, true); // Check if verification succeeded if ($verificationResult['success']) { // reCAPTCHA passed—proceed with your registration logic (user creation, etc.) // Example: save user to database, send confirmation email, etc. } else { // Verification failed—handle the error $error = "reCAPTCHA verification failed. Please try again."; // Optional: Log error codes for debugging (uncomment below) // error_log("reCAPTCHA errors: " . implode(", ", $verificationResult['error-codes'])); } } else { // No reCAPTCHA response was submitted $error = "Please complete the reCAPTCHA checkbox to continue."; }
While you asked for server-side changes, your frontend needs a quick update to work with v2:
- Replace your old v1 reCAPTCHA HTML with this v2 checkbox code:
<div class="g-recaptcha" data-sitekey="YOUR_V2_SITE_KEY"></div> <script src="https://www.google.com/recaptcha/api.js" async defer></script> - The v2 widget automatically adds the
g-recaptcha-responsefield to your form submission, so no extra work there as long as the widget is inside your form tag.
- Never hardcode your secret key in public-facing files—use environment variables if possible.
- Keep
CURLOPT_SSL_VERIFYPEERenabled to ensure you’re communicating securely with Google’s API. - Add rate limiting to your registration endpoint to prevent abuse, even with reCAPTCHA enabled.
If your hosting environment doesn’t have cURL enabled (uncommon but possible), you can use file_get_contents as a fallback:
$apiResponse = file_get_contents( 'https://www.google.com/recaptcha/api/siteverify?' . http_build_query($verificationData) );
But cURL is more reliable for handling HTTP requests, so I recommend using it if you can.
内容的提问来源于stack exchange,提问作者user3290060

