
Vuoi mettere un captcha su una pagina html e php con un form?
Ti spiego il modo più semplice e sicuro per aggiungere al tuo form un CAPTCHA in una pagina HTML + PHP: usare Google reCAPTCHA. Evita di reinventare la ruota ed è super affidabile.
Google reCAPTCHA v2
Ti consiglio di utilizzare Google reCAPTCHA v2 (“Non sono un robot”). Per utilizzarlo devi prima creare le chiavi su Google reCaptcha.
Vai quindi su https://www.google.com/recaptcha/admin, seleziona il tipo: reCAPTCHA v2, inserisci il sito su cui girerà la pagina con il form a cui applicherai il Captcha e riceverai i 2 codici Chiave:
Site key (frontend)
Secret key (backend)
Aggiungi il codice HTML alla pagina:
<!DOCTYPE html>
<html lang="it">
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form action="verifica.php" method="POST">
<input type="text" name="nome" required>
<div class="g-recaptcha" data-sitekey="LA_TUA_SITE_KEY"></div>
<button type="submit">Invia</button>
</form>
</body>
</html>
Nota: sostituisci LA_TUA_SITE_KEY quella appena generata su Google.
Lato PHP inserisci il seguente codice:
<?php
$secretKey = "LA_TUA_SECRET_KEY";
$responseKey = $_POST['g-recaptcha-response'];
$userIP = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify";
$data = [
'secret' => $secretKey,
'response' => $responseKey,
'remoteip' => $userIP
];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = json_decode($result);
if ($response->success) {
echo "Captcha valido ✅";
// qui continui con il tuo codice (salvataggi, email, ecc.)
} else {
echo "Captcha non valido ❌";
}
?>