Captcha Code in Codeigniter and jQuery

CAPTCHA is a simple test to determine if a user is a computer or a human. It is used to prevent spam abuse on the websites. So if you use CAPTCHA on your web site forms, this can help in stopping some bots and making life harder for other bots in accessing or using your forms.

In brief the CAPTCHA protection works by generating a random string, writing it to an image, then storing the string inside of a session or by some other method. This is then checked when the form is submitted.

HTML Code

<form class="form-horizontal" method="post" action="" onsubmit="return validateForm(this);">
	<div class="form-group">
		<label for="email" class="cols-sm-2 control-label">Your Email</label>
		<div class="cols-sm-10">
			<div class="input-group">
				<span class="input-group-addon"><i class="fa fa-envelope fa" aria-hidden="true"></i></span>
				<input type="text" class="form-control" name="email" id="email"  placeholder="Enter your Email"/>
			</div>
		</div>
	</div>

	<div class="form-group">
		<label for="username" class="cols-sm-2 control-label">Username</label>
		<div class="cols-sm-10">
			<div class="input-group">
				<span class="input-group-addon"><i class="fa fa-users fa" aria-hidden="true"></i></span>
				<input type="text" class="form-control" name="username" id="username"  placeholder="Enter your Username"/>
			</div>
		</div>
	</div>

	<div class="form-group">
		<label for="password" class="cols-sm-2 control-label">Password</label>
		<div class="cols-sm-10">
			<div class="input-group">
				<span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>
				<input type="password" class="form-control" name="password" id="password"  placeholder="Enter your Password"/>
			</div>
		</div>
	</div>

	<div class="form-group">
		<label class="control-label"></label>
		<div class="input-box">
			<div class="btn-group btn-input">

				<div id="imgdiv" style="display: inline;"><img id="img" src="<?= base_url() ?>captcha/getcapachaimage" /></div><img id="reload" src="<?= base_url() ?>img/reload.png" />	

			</div>
		</div>
	</div>
	<div class="form-group">
		<label class="control-label">Enter Image Text <sup>*</sup></label>
		<div class="input-box">
			<input type="text" class="form-control" id="captcha1"  >
			<div id="capacha_error" class="error_alertbox" style="display:none; color: red;"></div>
		</div>
	</div>

	<div class="form-group ">
		<button type="submit" class="btn btn-primary btn-lg btn-block login-button">Register</button>
	</div>

</form>

JavaScript / Jquery Code click on button and change captcha.

$("#reload").click(function () {
	$("img#img").remove();
	var id = Math.random();
	$('<img id="img" src="<?= base_url() ?>captcha/getcapachaimage?id=' + id + '"/>').appendTo("#imgdiv");
	id = '';
});

Button Click and refresh Captcha call in Controller function(captcha/getcapachaimage)

function getcapachaimage()
{
	$captchanumber = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz';
	$captchanumber = substr(str_shuffle($captchanumber), 0, 6);
	$_SESSION["code"] = $captchanumber;
	$path= base_url().'img/1.jpg';
	$image = imagecreatefromjpeg($path);
	$foreground = imagecolorallocate($image, 175, 199, 200); //font color
	imagestring($image, 5, 45, 8, $captchanumber, $foreground);
	header('Content-type: image/png');
	imagepng($image);
}

Submit button click and Form Validation

function validateForm(form) {
	var flag = 0;
	var status = false;
	var captcha = $('#captcha1').val();
	if (captcha == '') {
		flag = 1;
		var error_text = 'Please enter Image Text.';
		$('#capacha_error').html(error_text);
		$('#capacha_error').show();
	}
	if (flag == 1)
	{
		return status;
	} else
	{
		$.ajax({
			type: "POST",
			url: "<?= base_url() ?>captcha/checkcaptcha",
			global: false,
			data: {captcha: captcha},
			dataType: 'JSON',
			async: false, //blocks window close
			success: function (data) {
				if (data.error)
				{
					var error_text = 'Captcha Code does not Match Please check.';
					$('#capacha_error').html(error_text);
					$('#capacha_error').show();
					status = false;
				} else if (data.success)
				{
					status = true;
				}
			}
		});
		return status;
	}
}

Ajax Call in Controller function (captcha/checkcaptcha)

function checkcaptcha()
{	
	if ($_SESSION["code"] == $this->input->post('captcha')) {
		$json['success']  = true;
	} else {
		$json['error']  = true;
	}
	echo json_encode($json);
}

Leave a Reply

Your email address will not be published. Required fields are marked *