Protect a form with a captcha
Create site10 by copying site9.
- /cms
- ...
- site9
- site10
In this chapter, we are going to program a means to protect the site from robots which try to user a form.
Read the article Send an HTTP request to a web service to learn to write a program which exploits another application on the web.
To test the result online, enter http://www.frasq.org/cms/site10 in the address bar of your navigator. Fill in the form while copying the captcha in the input field to the right of the image. Send the form. Try sending the form without copying the captcha.
Start by creating an action called captcha
by adding the file captcha.php in the folder actions with the following content:
- /cms/site10
- actions
- captcha.php
- actions
- require_once 'strrand.php';
- require_once 'strtag.php';
- function captcha($lang) {
- $charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
- $code = strrand($charset, 4);
- $_SESSION['captcha'] = $code;
- $img = strtag($code);
- header('Content-Type: image/png');
- header("Content-Disposition: inline; filename=captcha.png");
- imagepng($img);
- imagedestroy($img);
- return false;
- }
The captcha
action generates a random code of 4 capital letters, memorizes it in the session and returns a document containing an image which displays the code.
To give access to the captcha
action, add an alias in the file includes/aliases.inc:
- $aliases = array(
- array(
- 'captcha' => 'captcha',
- ),
Notice that the alias doesn't depend on the language.
Add the files strrand.php and strtag.php in the folder library with the following contents:
- function strrand($charset, $len) {
- $max=strlen($charset)-1;
- $s = '';
- srand();
- for ($i=0; $i < $len; $i++) {
- $s .= $charset[rand(0, $max)];
- }
- return $s;
- }
strrand
returns a random sequence of characters taken from $charset
of length $len
.
- function strtag($text) {
- $len=strlen($text);
- $fontfile=ROOT_DIR . DIRECTORY_SEPARATOR . 'font.ttf';
- $fontsize=24.0;
- $bbox = imageftbbox($fontsize, 0, $fontfile, $text);
- $w=$bbox[2]+($len-1)*20;
- $h=40;
- $img = @imagecreatetruecolor($w, $h) or die();
- $bg=imagecolorallocate($img, 255, 255, 224);
- $fg=imagecolorallocate($img, 64, 64, 64);
- imagefill($img, 0, 0, $bg);
- // print text unevenly
- for ($x=15, $i=0; $i<$len; $i++) {
- $y = rand($h/2,$h/2+15);
- $r = rand(-45, 45);
- imagettftext($img, $fontsize, $r, $x, $y, $fg, $fontfile, $text[$i]);
- $x += rand(25, 35);
- }
- // blur with colored dots
- for ($i=0; $i<$w*$h/2.0; $i++) {
- $color=imagecolorallocate($img, rand(128,255), rand(128,255), rand(128,255));
- imagesetpixel($img, rand(0,$w-1), rand(0,$h-1), $color);
- }
- return $img;
- }
strtag
returns an image spotted with random color dots containing the characters of $text
sufficiently misplaced and rotated to make the text impossible to interpret by a program but still readable by a human.
Install the file of a TTF character font directly in the root directory of the site:
- /cms/site10
- font.ttf
Enter http://localhost/cms/site10/captcha in the address bar of your navigator to display the captcha. Press F5 to display another one.
To add a captcha to the contact page, modify the file mailme.phtml in the folder views/en:
- <p class="input">
- <img class="captcha" src="<?php echo $base_path; ?>/captcha/mailme" alt="" title="Verification code" />
- :
- <input type="text" name="mailme_code" id="mailme_code" size="4" maxlength="4" title="4 letters" onkeypress="return submitonenter(event, 'mailme_send')" value="" />
- </p>
Adds the captcha and the input field mailme_code
.
- <?php if ($missing_code): ?>
- <p>Enter the verification code displayed in the image.</p>
- <?php elseif ($bad_code): ?>
- <p>The verification code is incorrect.</p>
- <?php endif; ?>
Displays en error message if the code is missing or if it doesn't match the content of the image.
Modify the French version too:
- <p class="input">
- <img class="captcha" src="<?php echo $base_path; ?>/captcha/mailme" alt="" title="Code de vérification" />
- :
- <input type="text" name="mailme_code" id="mailme_code" size="4" maxlength="4" title="4 lettres" onkeypress="return submitonenter(event, 'mailme_send')" value="" />
- </p>
Notice that pressing return in the input field for the code sends the form.
- <?php if ($missing_code): ?>
- <p>Entrez le code de vérification affiché dans l'image.</p>
- <?php elseif ($bad_code): ?>
- <p>Le code de vérification est incorrect.</p>
- <?php endif; ?>
Modify the mailme
function in the file blocks/mailme.php to add the analysis of the captcha:
- $mail=$subject=$message=$code=false;
Initializes the variable which will hold the code returned by the form.
- if (isset($_POST['mailme_code'])) {
- $code=readarg($_POST['mailme_code'], true);
- }
Reads the code returned by the form.
- $missing_code=false;
- $bad_code=false;
Initializes the error flags.
- case 'send':
- if (!$code) {
- $missing_code=true;
- break;
- }
- $captcha=isset($_SESSION['captcha']) ? $_SESSION['captcha'] : false;
- if (!$captcha or $captcha != strtoupper($code)) {
- $bad_code=true;
- break;
- }
Checks if the code has been transmitted and if it matches the value memorized in the session.
- case 'send':
- if ($missing_code or $bad_code or $bad_mail or $missing_subject or $bad_subject or $missing_message) {
- break;
- }
Skips any further treatment if the code is missing or wrong. IMPORTANT: The program must leave as soon as possible if the captcha isn't valid.
- $errors = compact('missing_code', 'bad_code', 'missing_mail', 'bad_mail', 'missing_subject', 'bad_subject', 'missing_message', 'internal_error');
Adds the error flags $missing_code
and $bad_code
to the context of the view.
Modify the function bootstrap
in the file library/bootstrap.php to add the opening of a session:
- require_once 'session.php';
- function bootstrap() {
- global $base_url, $base_path, $base_root;
- global $session_name;
Loads the code which opens the session. Declares the global variable which holds the name of the session.
- if (!isset($session_name)) {
- list( , $session_name) = explode('://', $base_url, 2);
- $session_name = 'FQ' . $session_name;
- if (ini_get('session.cookie_secure')) {
- $session_name .= 'SSL';
- }
- }
- session_name(md5($session_name));
- session_open();
Builds a unique session name. Defines the name of the session for PHP. Note that if the name of the session is already defined, typically in the configuration file, it is preserved.
Add the file session.php in the folder library with the following content:
- function session_reopen() {
- session_close();
- session_open();
- }
- function session_open() {
- session_start();
- }
- function session_close() {
- session_destroy();
- $_SESSION=array();
- }
These 3 functions are simple wrappers which open and close the session.
IMPORTANT: The name of the session has been defined by the bootstrap
function.
Enter http://localhost/cms/site10/en/contact in the address bar of your navigator. Check that the form works if the code in the captcha is valid, missing or wrong.
Comments