TutorialMS Community Forum

Full Version: Working captcha for contact form
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Well, I've got the captcha working on my contact form Big Grin

The original captcha script comes from this site: http://www.white-hat-web-design.co.uk/ar...aptcha.php
Instructions are provided for script editing there.

**NOTE: copy your original templates and scripts as a backup before changing.

Download their zip file here: http://www.white-hat-web-design.co.uk/ar...aptcha.zip

I have changed the "CaptchaSecurityImages.php" sightly as follows:
Code:
<?php
session_start();

/*
* File: CaptchaSecurityImages.php
* Author: Simon Jarvis
* Copyright: 2006 Simon Jarvis
* Date: 03/08/06
* Updated: 07/02/07
* Requirements: PHP 4/5 with GD and FreeType libraries
* Link: http://www.white-hat-web-design.co.uk/articles/php-captcha.php
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
* http://www.gnu.org/licenses/gpl.html
*
*/

class CaptchaSecurityImages {

    var $font = 'monofont.ttf';

    function generateCode($characters) {
        /* list all possible characters, similar looking characters and vowels have been removed */
        $possible = '23456789AbcdEfghjkLmNpqRstvwxyz';
        $code = '';
        $i = 0;
        while ($i < $characters) {
            $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
            $i++;
        }
        return $code;
    }

    function CaptchaSecurityImages($width='120',$height='40',$characters='6') {
        $code = $this->generateCode($characters);
        /* font size will be 75% of the image height */
        $font_size = $height * 0.75;
        $image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream');
        /* set the colours */
        $background_color = imagecolorallocate($image, 255, 255, 255);
        $text_color = imagecolorallocate($image, 121, 151, 195);
        $noise_color = imagecolorallocate($image, 210, 218, 230);
        /* generate random dots in background */
        for( $i=0; $i<($width*$height)/3; $i++ ) {
            imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
        }
        /* generate random lines in background */
        for( $i=0; $i<($width*$height)/150; $i++ ) {
            imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
        }
        /* create textbox and add text */
        $textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function');
        $x = ($width - $textbox[4])/2;
        $y = ($height - $textbox[5])/2;
        imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function');
        /* output captcha image to browser */
        header('Content-Type: image/jpeg');
        imagejpeg($image);
        imagedestroy($image);
        $_SESSION['capcode'] = $code;
    }

}

$width = isset($_GET['width']) ? $_GET['width'] : '120';
$height = isset($_GET['height']) ? $_GET['height'] : '40';
$characters = isset($_GET['characters']) && $_GET['characters'] > 1 ? $_GET['characters'] : '6';

$captcha = new CaptchaSecurityImages($width,$height,$characters);

?>
On your root directory create the folder "captcha" with the edited "CaptchaSecurityImages.php" and the "monofont.ttf".

In your file "contact_us.php" replace the same start to end section with the following and save:
Code:
$messages['email_result'] = '';
if(isset($_POST['submit_email'])) {

    if($_POST['name'] == NULL || $_POST['email'] == NULL || $_POST['subject'] == NULL || $_POST['message'] == NULL) {
        $error = 1;
        $messages['email_result'] = '<span class="warningtext"><font color="#cc3333"><strong>One of the fields were left blank.</strong></font></span>
        <br />
        <br />';
    }    else if(!preg_match('/^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $_POST['email'])) {
        $error = 1;
        $messages['email_result'] = '<span class="warningtext"><font color="#cc3333"><strong>Please enter a valid email address.</strong></font></span>
        <br />
        <br />';
    }    else if( $_SESSION['capcode'] != $_POST['capcode'] || empty($_POST['capcode'] ) )  {
        $error = 1;
        $messages['email_result'] = '<span class="warningtext"><font color="#cc3333"><strong>The entered confirmation code was not valid.</strong></font></span>
        <br />
        <br />';
    }else{
        $error = 2;
        $name = check_slashes($_POST['name'], 2);
        $email = check_slashes($_POST['email'], 2);
        $subject = check_slashes($_POST['subject'], 2);
        $message = check_slashes($_POST['message'], 2);
    }
    if($error == 2) {
        $headers = 'From: '. $email . "\r\n" .
       'Reply-To: '.$email . "\r\n";
$full_message = 'This message was sent from your TutorialMS installtion\'s Contact Us page.
        
Sender\'s name: '.$name.'
Sender\'s email: '.$email.'
        
------------------------------------------------
'.$message.'
------------------------------------------------';
        
        mail($config['ADMIN_EMAIL'], $config['COMPANY_NAME'].' - '.$subject, $full_message, $headers);
        echo '<meta HTTP-EQUIV="REFRESH" content="0; url='.HTTP_SERVER.'contact_success.php">';
        echo 'Message sent successfully... you are now being redirected.<br />';        
    }
}
$subjects_un_parsed = $config['CONTACT_US_SUBJECTS'];
$exploded_subjects = explode(';', $subjects_un_parsed);
$bits['contact_us_subjects'] = '';
foreach($exploded_subjects as $value) {
    $bits['contact_us_subjects'] .= '<option value="'.$value.'">'.$value.'</option>';
}
Next save "contact_us.php" as "contact_success.php" and delete everything between the two lines:
Code:
require_once('includes/classes/tutorial.php');
/* AND */
echo template(CURRENT_STYLE_ID, 'header');
Next change the following section in "contact_success.php":
Code:
echo template(CURRENT_STYLE_ID, 'column_middle_start');
echo template(CURRENT_STYLE_ID, 'contact_us_break');
echo template(CURRENT_STYLE_ID, 'contact_us');
echo template(CURRENT_STYLE_ID, 'column_middle_end');
to the following:
Code:
echo template(CURRENT_STYLE_ID, 'column_middle_start');
echo template(CURRENT_STYLE_ID, 'contact_success_break');
echo template(CURRENT_STYLE_ID, 'contact_success');
echo template(CURRENT_STYLE_ID, 'column_middle_end');
Finally, in the admin CP create the following templates:
"contact_success_break":
Code:
<div class="thead">
<!-- THIS IS COMMENTED OUT BECAUSE I DID NOT USE AN ICON
    <img src="$config[HTTP_SERVER]images/header_icons/contact.gif" alt="Contact Us" style="margin-right:10px;" />
REMOVE THESE COMMENTS AND TAGS TO USE AN IMAGE-->
<strong>Contact Successful</strong>
</div>
<div class="genmcontainer">
"contact_success"
Code:
<span class="normaltext">
<b><font color="#cc3333" size="2">Your message was successfully sent.</font></b></span>
<br /><br />
                  <center><b><font size="2">Your contact is important to us.</font></b>
            <br /><br />We appreciate all input and suggestions<br />and will respond at our earliest opportunity</center>
            <br /><br />
</div>
Now edit the template "contact_us" (replace the entire template with the following):
Code:
<span class="normaltext">
$messages[email_result]Select a subject from the drop-down and then fill out the text area and your message will be emailed to the administrator.</span>
<br /><br />
<if condition="$config[MOD_REWRITE_ON] == 1">
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<else />
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
</if>
    <div class="contact">Your Name:</div>
    <div style="float: left;"><input type="text" class="form_styles" size="50" name="name" value="<?=$_POST['name'] ?>" /></div>
    <div style="clear: both;"></div>
    <br />
    <div class="contact">Your E-mail Address:</div>
    <div style="float: left;"><input type="text" class="form_styles" size="50" name="email" value="<?=$_POST['email'] ?>" /></div>
     <div style="clear: both;"></div>
     <br />
    <div class="contact">Subject:</div>
    <div style="float: left;"><select name="subject" class="form_styles">
      $bits[contact_us_subjects]
    </select></div>
     <div style="clear: both;"></div>
     <br />
    <div class="contact">Your Message:</div>
    <div style="float: left;"><textarea name="message" class="form_styles" rows="7" cols="50"><?=$_POST['message'] ?></textarea></div>
     <div style="clear: both;"></div>
     <br />
                  <center><b><font color="#cc3333">Confirmation Code</font></b><br /><img src="$config[HTTP_SERVER]captcha/CaptchaSecurityImages.php?width=70&height=30&characters=5"
alt="confirmation" /><br /><i><font size="1">(Code is case sensitive)</font></i><br
/><input class="form_styles" type="text" name="capcode" size="10"  /><br /><font color="#cc3333" size="1">Enter the confirmation code into the text box, then Send.</font><br />
<br />
      <center><input type="submit" class="form_styles" value="Send" name="submit_email" /></center><br /><br /><i><font size="1">All submitted information is held in strict confidence.</font></i>
</div>
This enables captcha verification as well as remembering form fields if an error was in the submission so the visitor doesn't need to re-enter everything. It also confirms a valid email address in the form.

I've tested on my contact form and it worked in all trials. I'll also post a link when my site goes public ... hopefully in the next few days.

Hope this helps.
The website has gone public now and I've posted the link in the showcase. To look at the contact form: http://www.usertutor.com/contact_us.php

Hope this helps.

Edit: This link seems to no longer be working.
Stickied. Great post!
(12-19-2008 04:26 AM)utjames Wrote: [ -> ]The website has gone public now and I've posted the link in the showcase. To look at the contact form: http://www.usertutor.com/contact_us.php

Hope this helps.

Edit: This link seems to no longer be working.

Here's the new link:
http://www.usertutor.org/contact_us.php
Reference URL's