Skip to content

Instantly share code, notes, and snippets.

@jgauthi
Last active June 13, 2021 12:09
Show Gist options
  • Save jgauthi/1201de2c0445cd95f75ad1c1a442280b to your computer and use it in GitHub Desktop.
Save jgauthi/1201de2c0445cd95f75ad1c1a442280b to your computer and use it in GitHub Desktop.
Form validation with HCAPTCHA (google recaptcha alternative)
<?php
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
// Complete configuration: https://hcaptcha.com
const HCAPTCHA_SECRET_KEY = '...';
const HCAPTCHA_API_KEY = '...';
/**
* @throws Exception
* @throws TransportExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
*/
function checkForm(array $postData): ?bool
{
if (!empty($postData['email'])
&& filter_var($postData['email'], FILTER_VALIDATE_EMAIL)
) {
// https://docs.hcaptcha.com/
if (!empty(HCAPTCHA_SECRET_KEY) && !empty(HCAPTCHA_API_KEY)) {
if (empty($_POST['h-captcha-response'])) {
throw new InvalidArgumentException('Captcha empty, have you completed this test ?');
}
$client = HttpClient::create();
$response = $client->request( 'POST', 'https://hcaptcha.com/siteverify', [
'body' => [
'secret' => HCAPTCHA_SECRET_KEY,
'sitekey' => HCAPTCHA_API_KEY,
'response' => $_POST['h-captcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR'],
],
] );
$return = $response->toArray();
if (!isset($return['success']) || !$return['success']) {
$error = !empty($return['error-codes'])
? 'Error codes: '.implode(', ', $return['error-codes'])
: 'No code returned by the API';
throw new Exception($error);
}
}
// form check [...]
return true;
}
return null;
}
?><html>
<head>
<title>hCaptcha Demo</title>
<script src="https://hcaptcha.com/1/api.js" async defer></script>
</head>
<body>
<?php
if ('POST' == $_SERVER['REQUEST_METHOD']) {
try {
if ( checkForm($_POST) ) {
echo '<p>OK.</p>';
} else {
echo '<p>Error during form validation.</p>';
}
} catch ( Throwable $exception ) {
?>
<p>Error during form validation: <?=$exception->getMessage()?></p>
<?php
}
} else {
?><form action="<?=$_SERVER['REQUEST_URI']?>" method="POST">
<input type="text" name="email" placeholder="Email" />
<?php if (!empty(HCAPTCHA_SECRET_KEY) && !empty(HCAPTCHA_API_KEY)): ?>
<div class="h-captcha" data-sitekey="<?=HCAPTCHA_API_KEY?>"></div>
<?php endif ?>
<br />
<input type="submit" value="Submit" />
</form>
<?php } ?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment