23
Dec
2014

Simple captcha using PHP sessions

Demo | Source

In this article I will show how to create a Simple captcha using PHP sessions. The captcha will simply ask for the answer to a randomly set math question.

On the very first line of your php file add the following line.


session_start();

Next we check if the session variables for the captcha sum are set and if not we’ll set them. We set them to both to a random number between 1 and 5.


if (!isset($_SESSION['num1']) && !isset($_SESSION['num2'])) {
    $_SESSION['num1'] = rand(1, 5);
    $_SESSION['num2'] = rand(1, 5);
}

We start off with the HTML for the form. I just grabbed a code snippet to create the form but you can add this to any form.


<form action="validate.php" method="post" class="basic-grey">
<h1>Contact Form</h1>
	<label>
		<span>Your Name :</span>
		<input id="name" type="text" name="name" placeholder="Your Full Name" />
	</label>
	<label>
		<span>Your Email :</span>
		<input id="email" type="email" name="email" placeholder="Valid Email Address" />
	</label>
	<label>
		<span>Message :</span>
		<textarea id="message" name="message" placeholder="Your Message to Us"></textarea>
	</label>
	<label>
		<span>Subject :</span>
                <select name="selection">
			<option value="Job Inquiry">Job Inquiry</option>
			<option value="General Question">General Question</option>
		</select>
	</label>    
	// Captcha goes here
	<label>
		<span> </span> 
		<input type="submit" class="button" value="Send" name="submit_form" /> 
	</label>    
</form>

Now we'll add the label and input for the captcha. Replace // Captcha goes here with the following


 <label>
    <span><?php echo $_SESSION['num1']; ?> + <?php echo $_SESSION['num2']; ?>?</span>
    <input id="captcha" type="text" name="captcha" placeholder="<?php echo $_SESSION['num1']; ?> + <?php echo $_SESSION['num2']; ?>?" />
</label>

The CSS for the code snippet.


/* Basic Grey */
.basic-grey {
    margin-left:auto;
    margin-right:auto;
    max-width: 500px;
    background: #F7F7F7;
    padding: 25px 15px 25px 10px;
    font: 12px Georgia, "Times New Roman", Times, serif;
    color: #888;
    text-shadow: 1px 1px 1px #FFF;
    border:1px solid #E4E4E4;
}
.basic-grey h1 {
    font-size: 25px;
    padding: 0px 0px 10px 40px;
    display: block;
    border-bottom:1px solid #E4E4E4;
    margin: -10px -15px 30px -10px;;
    color: #888;
}
.basic-grey h1>span {
    display: block;
    font-size: 11px;
}
.basic-grey label {
    display: block;
    margin: 0px;
}
.basic-grey label>span {
    float: left;
    width: 20%;
    text-align: right;
    padding-right: 10px;
    margin-top: 10px;
    color: #888;
}
.basic-grey input[type="text"], .basic-grey input[type="email"], .basic-grey textarea, .basic-grey select {
    border: 1px solid #DADADA;
    color: #888;
    height: 30px;
    margin-bottom: 16px;
    margin-right: 6px;
    margin-top: 2px;
    outline: 0 none;
    padding: 3px 3px 3px 5px;
    width: 70%;
    font-size: 12px;
    line-height:15px;
    box-shadow: inset 0px 1px 4px #ECECEC;
    -moz-box-shadow: inset 0px 1px 4px #ECECEC;
    -webkit-box-shadow: inset 0px 1px 4px #ECECEC;
}
.basic-grey textarea{
    padding: 5px 3px 3px 5px;
}
.basic-grey select {
    background: #FFF url('down-arrow.png') no-repeat right;
    background: #FFF url('down-arrow.png') no-repeat right;
    appearance:none;
    -webkit-appearance:none; 
    -moz-appearance: none;
    text-indent: 0.01px;
    text-overflow: '';
    width: 70%;
    height: 35px;
    line-height: 25px;
}
.basic-grey textarea{
    height:100px;
}
.basic-grey .button {
    background: #E27575;
    border: none;
    padding: 10px 25px 10px 25px;
    color: #FFF;
    box-shadow: 1px 1px 5px #B6B6B6;
    border-radius: 3px;
    text-shadow: 1px 1px 1px #9E3F3F;
    cursor: pointer;
}
.basic-grey .button:hover {
    background: #CF7A7A
}

Validating the captcha

In our validation file we again start with beginning the session.


session_start();

We check that the session variables for our captcha are set. If they are not set then we cannot validate the captcha or the form so we redirect back to our form page and set an error in a session variable.


if (!isset($_SESSION['num1']) || !isset($_SESSION['num2'])) {
    // no known session. cannot validate captcha
    $_SESSION['error']['captcha'] = 'Cannot validate captcha.';
    
    // here any post variables are sent back in a session so user does not lose their input
    foreach ($_POST as $key => $value) {
        if (!is_array($_POST[$key])) {
            $$key = addslashes($value);
            $_SESSION['form'][$key] = $value;
        }
    }

    header('Location: index.php');
    exit;
}

If the session variables are set then we then we create a variable to store the sum of the two variables.


$sum = (int) $_SESSION['num1'] + (int) $_SESSION['num2'];

Now we check that the captcha field has been filled out that the the value is equal to the $sum variable. If the variable is set but does not equal the $sum variable then we again assign the post vaiables to a session array and redirect back to the form.


if (isset($_POST['captcha']) && (int) $_POST['captcha'] !== $sum) {
    // captcha given but incorrect
    $_SESSION['error']['captcha'] = 'Captcha incorrect.';
    foreach ($_POST as $key => $value) {
        if (!is_array($_POST[$key])) {
            $$key = addslashes($value);
            $_SESSION['form'][$key] = $value;
        }
    }

    header('Location: index.php');
    exit;
} else {
    // captcha correct, show a new one next time
    unset($_SESSION['num1'], $_SESSION['num2']);
    //process form ...
}

I've omitted the rest of the validation but the full code for the demo is up on github.

Share

You may also like...