0

Hi all,

I tried to do a CAPTCHA "error message - I would like an error message (pop up) show on the first page (checkForm.php) when user entered a wrong code/secureimage. At the moment the error message showing on the next page (processFrom.php) which isn't really what I want.

Can anyone show me what is the correct way to achieve what I need please?

Here I show you the snippets of the code:
checkForm.php

<?php
session_start();
require("include/application_top.php");

?>
<head>
<script type="text/javascript">
 
$(document).ready(function(){
 
  $('#btn_submit').click(function() {
    var error_num = 0;
    var error_mesg = "";
    
    $('[name=name]').parent().removeClass('error');
    if($('[name=name]').val()==""){
      error_num++;
      error_mesg += "Please enter your name \n";
      $('[name=name]').parent().addClass('error');
    }
    
    $('[name=tel]').parent().removeClass('error');
    if($('[name=tel]').val()==""){
      error_num++;
      error_mesg += "Please enter telephone no\n";
      $('[name=tel]').parent().addClass('error');
    }
    
	$('[name=captcha_code]').parent().removeClass('error');
    if($('[name=captcha_code]').val()==""){
      error_num++;
      error_mesg += "Please enter the image verification\n";
      $('[name=captcha_code]').parent().addClass('error');
    }
    
..
..
..
    
  });
 
});
</script>
</head>
<body>
 

<form name="check_form" id="check_form" method="post" action="processForm.php">
 
<table width="100%" border="0" cellspacing="5" cellpadding="0">
  <tr>
    <td width="20%">Name</td>
    <td width="80%"><input name="name" type="text" id="name" size="30" /></td>
  </tr>
  <tr>
    <td>Tel</td>
    <td><input name="tel" type="text" id="tel" size="30" /></td>
  </tr>
 
</table>
 
<dl>
Please enter the text that you see in the image into the box on below. 
</dl>
 
<table width="100%" border="0" cellspacing="5" cellpadding="0">
  <tr>
    <td width="20%"><input type="text" name="captcha_code" size="20" maxlength="6" />
<a href="#">
[ Different Image ]</a></td>
    <td width="80%"><img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image"/></td>
  </tr>
</table>
 
 
<div class="btn"><input name="btn_submit" type="button" id="btn_submit" value="Submit" /></div>
</div>
</form>

</body>
</html>

processForm.php

<?php
session_start();
require("include/application_top.php");
 
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
   //echo "The security code entered was incorrect.<br /><br />";
  echo "The code you entered was incorrect. Please go <a href='javascript:history.go(-1)'>back</a> and try again. ";
  exit;
}

..
..
<!--SNIPPETS DATABASE CONNECTION-->
$table_fields = array("name", "tel");
..
..
  $connection = mysql_connect (DB_SERVER, DB_USER, DB_PASS) or
	die ('I cannot connect to the database because: ' . mysql_error());
  mysql_select_db (DB_NAME, $connection);
  mysql_query ($query, $connection)
	or die(mysql_error()."\n<br />This is the query:\n<br />".$query);
..
..
  
  header ("Location:thankyou.php");
  
}
?>

Edited by siabenie: n/a

2
Contributors
48
Replies
49
Views
6 Years
Discussion Span
Last Post by siabenie
0

Siabenie,

You appear to have the necessary coding skills but just need clarification on how to make the form validation process hang together. I will therefore attempt to talk you through it without offering any code.

The model that you appear to need (and is typical) is one in which failure to validate on any single aspect will suppress form submission; one of the aspects to be considered being CAPTCHA.

If I understand correctly, you currently perform the server-side CAPTCHA test by submitting the form, thus guaranteeing that the page is renewed.

What you need to do is to perform the server-side CAPTCHA test without submitting the form; hence it must be done with AJAX. jQuery makes the client-side code simple - see jQuery documentation.

What is maybe not so obvious is how to handle the asynchronicity of the CAPTCHA test (which is inevitable from AJAX), alongside the synchronicity of the other validation tests.

This is actually also quite simple.

  1. Ensure that the synchronous validation process neither causes nor allows the form to be submitted.
  2. Ensure that the overall result of the synchronous validation process (pass/fail) is made available to the CAPTCHA's AJAX success handler; typically this is automatically achieved by the validation function forming a closure around the AJAX function and its success handler - hence no need for global variables.
  3. Ensure that the CAPTCHA's AJAX success handler takes into account both the AJAX response AND the the overall result of the synchronous validation process.
  4. Still inside the AJAX success handler: If the CAPTCHA test result is "fail", then indicate the error condition for CAPTCHA failure. If the super-overall result is "pass", then force the form to submit, or do whatever else is required with the valid form (eg. initiate another AJAX call to handle the form data).

The model gets very slightly more involved if more than one asynchronous test must be performed.

Airshow

Edited by Airshow: n/a

0

Thanks Airshow for the feedback, the problem that I am having is I do not know how AJAX works and I am very new in PHP and jQuery.

Would you please mind show me how I can do this? I have been trying to find few tips online but no success so far.

I would be very much appreciated if you could show me some code how to solve this issue.

Thank you.

0

Siabenie,

I will see what I can do but no time right now. Maybe this evening (UK time).

Meanwhile I suggest you read the AJAX section of the jQuery API. Of the settings, you will probably need only url, success and error, maybe type - for all the other settings, default values/behaviour will probably suffice.

Also make sure you understand what I said in my post above.

Airshow

Edited by Airshow: n/a

0

Siabenie,

I will see what I can do but no time right now. Maybe this evening (UK time).

Meanwhile I suggest you read the AJAX section of the jQuery API. Of the settings, you will probably need only url, success and error, maybe type - for all the other settings, default values/behaviour will probably suffice.
Airshow

Hi Airshow,

Thanks again, I will look up the link. Few questions: What you mean by "of the setting" which setting? I'm the same as local time as you so I hope you be able to assist me.

There are few things that I do not get what you mean on your previous msg;

What you need to do is to perform the server-side CAPTCHA test without submitting the form; hence it must be done with AJAX. jQuery makes the client-side code simple - see jQuery documentation.

Are you saying that I should not redirect the form to the next page(processForm.php)? The problem is I am very new in web app so please excuse if I am being bit nuisance.

What is maybe not so obvious is how to handle the asynchronicity of the CAPTCHA test (which is inevitable from AJAX), alongside the synchronicity of the other validation tests.

I'm not so sure what you mean by asynchronicity and synchronicity here?

Thanks again, hear from you soon.

0

Hi Airshow,

I see what you mean by "Of setting" -- Will look at the jQuery doc now.

Will keep you posted.

0

Hi Airshow,

I have added these snippets code below - but when I entered a wrong code the form still proceed to thankyou.php instead of showing me an error.

I have change the HTML and code slight (from the previous I shown here) not sure what I did wrong this time. :(
Can you please have a look and let me know please?

checkFrom.php

<script type="text/javascript">

$(document).ready(function(){

  $('#btn_submit').click(function() {
    var error_num = 0;
    var error_mesg = "";
  

    $('[name=name]').parent().removeClass('error');
    if($('[name=name]').val()==""){
      error_num++;
      error_mesg += "Please enter your name\n";
      $('[name=name]').parent().addClass('error');
    }

 $('[name=tel]').parent().removeClass('error');
    if($('[name=tel]').val()==""){
      error_num++;
      error_mesg += "Please enter tel no\n";
      $('[name=tel]').parent().addClass('error');
    }
	$('[name=captcha_code]').parent().removeClass('error');
    if($('[name=captcha_code]').val()==""){
      error_num++;
      error_mesg += "Please enter the image verification\n";
      $('[name=captcha_code]').parent().addClass('error');
    }
	
	$.presents_process_c("presents_process_c.php?"+$("#present_form").serialize(), {
		
			}, function(response){
			
			if(response==1)
			{
				$("#after_submit").html('');
				$("#btn_submit").after('<label class="success" id="after_submit">Your message has been submitted.</label>');
				change_captcha();
				//clear_form();
			}
			else
			{
				$("#after_submit").html('');
				$("#btn_submit").after('<label class="error" id="after_submit">Error ! invalid captcha code .</label>');
			}
			
			
		});
    
    if(error_num>0){
      alert(error_mesg);
    }else if(error_num==0){
     
      $('#present_form').submit();
     
    }
    return false;
    
  });
  
  // refresh captcha
	 $('img#refresh').click(function() {  
			
			change_captcha();
	 });
	 
	 function change_captcha()
	 {
	 	document.getElementById('captcha').src="get_captcha.php?rnd=" + Math.random();
	 }
	 

});
</script>

<!--Snippets of HTML CODE-->
<form name="present_form" id="present_form" method="post" action="processForm.php">

<table width="100%" border="0" cellspacing="5" cellpadding="0">
  <tr>
    <td width="20%">Name</td>
    
	<td width="80%"><input name="name" type="text" id="name" size="30" /></td>
  </tr>
  <tr>
    <td>Tel</td>
    <td><input name="tel" type="text" id="tel" size="30" /></td>
  </tr>
</table>

<dl>
Please enter the text that you see in the image into the box on below. 
</dl>

<table width="100%" border="0" cellspacing="5" cellpadding="0">

	<div id="wrap" align="center">
		<img src="get_captcha.php" alt="" id="captcha" />
		
		<br clear="all" />
		<input type="text" name="captcha_code" size="20" maxlength="6" />
		<!--input name="code" type="text" id="code"-->
	</div>
	<img src="refresh.jpg" width="25" alt="" id="refresh" />
</table>

<div class="btn">
   <input name="btn_submit" type="button" id="btn_submit" value="Submit" />
</div>

get_captcha.php

<?php
session_start();

$string = '';

for ($i = 0; $i < 5; $i++) {
	$string .= chr(rand(97, 122));
}

$_SESSION['random_number'] = $string;

$dir = 'fonts/';

$image = imagecreatetruecolor(165, 50);

// random number 1 or 2
$num = rand(1,2);
if($num==1)
{
	$font = "Capture it 2.ttf"; // font style
}
else
{
	$font = "Molot.otf";// font style
}

// random number 1 or 2
$num2 = rand(1,2);
if($num2==1)
{
	$color = imagecolorallocate($image, 113, 193, 217);// color
}
else
{
	$color = imagecolorallocate($image, 163, 197, 82);// color
}

$white = imagecolorallocate($image, 255, 255, 255); // background color white
imagefilledrectangle($image,0,0,399,99,$white);

imagettftext ($image, 30, 0, 10, 40, $color, $dir.$font, $_SESSION['random_number']);

header("Content-type: image/png");
imagepng($image);

?>

processForm.php

<?php
session_start();
require("include/application_top.php");

if(@$_REQUEST['captcha_code'] || @strtolower($_REQUEST['captcha_code']) == strtolower($_SESSION['random_number']))
	{
	
$table_fields = array("name", "tel");
$table_name = "present";

$CHARSET_ENCODING="UTF-8";
$EMAIL_HEADER_EOL="\n";
$form_num = 1;
if(isset($_GET['form_num']) && $_GET['form_num']==2){
  $form_num = 2;//$_GET['form_num'];
}
mb_internal_encoding($CHARSET_ENCODING);

$standard_emailheaders="MIME-Version: 1.0".$EMAIL_HEADER_EOL;
$standard_emailheaders.="X-Mailer: PHP/".phpversion().$EMAIL_HEADER_EOL;
$standard_emailheaders.="Content-type: text/plain; charset=\"".$CHARSET_ENCODING."\"".$EMAIL_HEADER_EOL;
$standard_emailheaders.="Content-Transfer-Encoding: 8bit";


if(isset($_POST['name'])){
  
  $connection = mysql_connect (DB_SERVER, DB_USER, DB_PASS) or
	die ('I cannot connect to the database because: ' . mysql_error());
  mysql_select_db (DB_NAME, $connection);
  $query = "INSERT INTO .....";
  foreach ($table_fields as $field_name) {
      $http_var = $field_name;
      $http_val = (isset($_POST[$http_var]) ? httpreqvar_strip($_POST[$http_var]) : "");
      $value = $http_val;
      if($field_name=="email_list" && $value=="") $value="n";
	    $query .= ", $field_name='".mysql_real_escape_string($value)."'";
  }
  
  mysql_query ($query, $connection)
	or die(mysql_error()."\n<br />This is the query:\n<br />".$query);
  $last_inserted_id = mysql_insert_id();
  
  $notification_to="yourmailaddress@mail.com";
  $notification_subject=" Present Application Received";
  mail($notification_to, $notification_subject);
  
  header ("Location: thankyou.php");
	}
		
 }
	else
	{
    header('Location: processForm.php?retry=yes');
	}

?>
0

Siabenie,

I will see what I can do but no time right now. Maybe this evening (UK time).

Meanwhile I suggest you read the AJAX section of the jQuery API. Of the settings, you will probably need only url, success and error, maybe type - for all the other settings, default values/behaviour will probably suffice.

Also make sure you understand what I said in my post above.

Airshow

Hi Airshow,

I wonder if you have got time to review about my question please?

Thanks.

0

Siabene,

Sorry I didn't have time yesterday. I'm on holiday and, having paid for the flight, feel the need to do lots of sightseeing and get lots of fresh air.

I will see what I can do later today.

Airshow

0

Siabene,

Sorry I didn't have time yesterday. I'm on holiday and, having paid for the flight, feel the need to do lots of sightseeing and get lots of fresh air.

I will see what I can do later today.

Airshow

I see, lucky you I can understand - well please get back to me when you can, really appreciated it.

Meanwhile, enjoy your holiday and bring some sun when you are back! We need it lols!

0

Siabene,

OK here's something for starters. Probably not 100% yet but should at least demonstrate the general pattern.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
.error { background-color: red; }
</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
  var $form = $("[name='present_form'")
  var $tel = $("[name='tel']");
  var $name = $("[name='name']");
  var $captcha_code = $("[name='captcha_code']");
  var captcha_verified = false;
  
  $('#btn_submit').click(function() {
    var error_mesg = [];

    if($name.val()===""){
      error_mesg.push("Please enter your name");
      $name.parent().addClass('error');
    }
	else {
      $name.parent().removeClass('error');
    }

    if($tel.val()==""){
      error_mesg.push("Please enter tel no");
      $tel.parent().addClass('error');
    }
	else {
      $tel.parent().removeClass('error');
    }

    if(!captcha_verified){
      $captcha_code.parent().removeClass('error');
      if($captcha_code.val()===""){//user HAS NOT attempted the captcha
        error_mesg.push("Please enter the image verification");
        $captcha_code.parent().addClass('error');
        alert(error_mesg.join("\n"));
      }
      else{//user HAS attempted the captcha
        $.ajax({
          url: "verify_captcha.php",
          type: "POST",
          data: {code: $captcha_code.val()},
          success: function(response){
            alert('ajax success: ' + $captcha_code.val());//debug statement
            if(Number(response)==='1'){//captcha correct
              captcha_verified = true;
              $captcha_code.attr('disabled',true);
              if(error_mesg.length===0){
                $form.get(0).submit();//Hooray, everything verified - submit the form.
              }
            }
            else{//captcha failed
              error_mesg.push("Image verification failed.");
              $captcha_code.parent().addClass('error');
              change_captcha();//change capture on failure, otherwise a clever bot could crack the captcha code with multiple attempts.
            }
          },
          error: function(){
            alert('ajax error: ' + $captcha_code.val());//debug statement
            error_mesg.push("Your image verification code may be correct but an error occurred while verifying it.");
          },
          complete: function(){
            alert('ajax complete: ' + $captcha_code.val());
            if(error_mesg.length > 0){
              alert(error_mesg.join("\n"));
            }
          }
        });
      }
    }
    return false;
  });
  
  function change_captcha(){
    document.getElementById('captcha').src="get_captcha.php?rnd=" + Math.random();
  }
  $('img#refresh').click(change_captcha);
});
</script>
</head>

<body>

<!--Snippets of HTML CODE-->
<form name="present_form" id="present_form" method="post" action="processForm.php">

<table width="100%" border="0" cellspacing="5" cellpadding="0">
  <tr>
    <td width="20%">Name</td>
	<td width="80%"><input name="name" type="text" id="name" size="30" /></td>
  </tr>
  <tr>
    <td>Tel</td>
    <td><input name="tel" type="text" id="tel" size="30" /></td>
  </tr>
</table>

<dl>Please enter the text that you see in the image into the box on below.</dl>

<table width="100%" border="0" cellspacing="5" cellpadding="0">
	<div id="wrap" align="center">
		<img src="get_captcha.php" alt="" id="captcha" />
		<br clear="all" />
		<input type="text" name="captcha_code" size="20" maxlength="6" />
		<!--input name="code" type="text" id="code"-->
	</div>
	<img src="refresh.jpg" width="25" alt="" id="refresh" />
</table>

<div class="btn">
   <input name="btn_submit" type="button" id="btn_submit" value="Submit" />
</div>

</form>

</body>
</html>

NOTES:

  • error_mesg is now an array
  • error_no is no longer necesary
  • New script "verify_captcha.php" needs to be written
  • For some reason the ajax success fires even when "verify_captcha.php" doesn't exist
  • Does change_captcha() work?
  • Need to reverify the captcha when form is submitted, otherwise the check could be easily defeated.
  • I have not looked at the server-side scripts

Airshow

0

Thanks Airshow for the kind feedback,

I have to say the way you wrote the code much clearer than mine.. I am currently trying to work it out and will get back to you asap.

Will keep you posted.
Thanks.

PS: Airshow, I would like to use the code from http://www.phpcaptcha.org/ and put in my code, I will try to show you what I mean once I have put them together.

Edited by siabenie: n/a

0

Hi Airshow,

I have tried to put the code together: but it does not look like what it appears to be...

Yes the change_captcha does work, the image does change.

I think I did show you the snippets for verify_captcha.php? I am not sure what I did here is correct; but I created the processForm.php as shown. Is it consider as verify_captcha.php? Please let me know.

Thanks!

processForm.php

<?php
session_start();
require("include/application_top.php");

if(@$_REQUEST['captcha_code'] || @strtolower($_REQUEST['captcha_code']) == strtolower($_SESSION['random_number']))
	{
	
$table_fields = array("name", "tel");
$table_name = "testing";

$CHARSET_ENCODING="UTF-8";
$EMAIL_HEADER_EOL="\n";

mb_internal_encoding($CHARSET_ENCODING);

$standard_emailheaders="MIME-Version: 1.0".$EMAIL_HEADER_EOL;
$standard_emailheaders.="X-Mailer: PHP/".phpversion().$EMAIL_HEADER_EOL;
$standard_emailheaders.="Content-type: text/plain; charset=\"".$CHARSET_ENCODING."\"".$EMAIL_HEADER_EOL;
$standard_emailheaders.="Content-Transfer-Encoding: 8bit";


if(isset($_POST['name'])){
  
  $connection = mysql_connect (DB_SERVER, DB_USER, DB_PASS) or
	die ('I cannot connect to the database because: ' . mysql_error());
  mysql_select_db (DB_NAME, $connection);
  $query = "INSERT INTO .....";
  foreach ($table_fields as $field_name) {
      $http_var = $field_name;
	    $query .= ", $field_name='".mysql_real_escape_string($value)."'";
  }
  
  mysql_query ($query, $connection)
	or die(mysql_error()."\n<br />This is the query:\n<br />".$query);
  $notification_to="yourmailaddress@mail.com";
  $notification_subject=" Present Application Received";
  mail($notification_to, $notification_subject);
  
  header ("Location: thankyou.php");
	}
		
 }
	else
	{
    header('Location: checkForm.php?retry=yes');
	}

?>

Edited by siabenie: n/a

0

Siabenie,

As I conceived it (and as I coded the javasccript), verify_captcha.php should simply return:-

  • '0' for fail
  • '1' for pass

My code makes no assumptions about processForm.php, except that it should re-verify the captcha. It should return the original page (containing "present_form") if it fails.

When I asked, "does change_captcha() work?", I was really prompting you to make sure that the get_captcha.php script stores the generated captcha string server-side (in $_SESSION) so that verify_captcha.php and processForm.php can later perform the captcha verification test. Now that I can see processForm.php, I can tell that this aspect is probably correct.

Airshow

0

Siabenie,

As I conceived it (and as I coded the javasccript), verify_captcha.php should simply return:-

  • '0' for fail
  • '1' for pass

My code makes no assumptions about processForm.php, except that it should re-verify the captcha. It should return the original page (containing "present_form") if it fails.

When I asked, "does change_captcha() work?", I was really prompting you to make sure that the get_captcha.php script stores the generated captcha string server-side (in $_SESSION) so that verify_captcha.php and processForm.php can later perform the captcha verification test. Now that I can see processForm.php, I can tell that this aspect is probably correct.

Airshow

Thanks Airshow, I am very new about web app and my knowledge about programming is very limited sorry if I did not get what you trying to explain.

Anyway, I have tried to put all the code but it does not work - not sure what I did wrong now. Can you please show me if this verify_captcha.php is correct:

<?php
	session_start();
	
if(@$_REQUEST['captcha_code'] || @strtolower($_REQUEST['captcha_code']) == strtolower($_SESSION['random_number']))
	{
      // insert your name , email and text message to your table in db
		echo 1;// submitted 
	}
	else
	{
		echo 0; // invalid code
	}
	?>

Thanks and really appreciate your help.

0

Here are my code; Please can you see what I did wrong?

I have also attached the refresh.jpg image on my folder - still I am confused where was the mistake - sorry I am very new in this coding. But thanks for your kind help.

checkForm.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
.error { background-color: red; }
</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
  var $form = $("[name='present_form'")
  var $tel = $("[name='tel']");
  var $name = $("[name='name']");
  var $captcha_code = $("[name='captcha_code']");
  var captcha_verified = false;
  
  $('#btn_submit').click(function() {
    var error_mesg = [];

    if($name.val()===""){
      error_mesg.push("Please enter your name");
      $name.parent().addClass('error');
    }
	else {
      $name.parent().removeClass('error');
    }

    if($tel.val()==""){
      error_mesg.push("Please enter tel no");
      $tel.parent().addClass('error');
    }
	else {
      $tel.parent().removeClass('error');
    }

    if(!captcha_verified){
      $captcha_code.parent().removeClass('error');
      if($captcha_code.val()===""){//user HAS NOT attempted the captcha
        error_mesg.push("Please enter the image verification");
        $captcha_code.parent().addClass('error');
        alert(error_mesg.join("\n"));
      }
      else{//user HAS attempted the captcha
        $.ajax({
          url: "verify_captcha.php",
          type: "POST",
          data: {code: $captcha_code.val()},
          success: function(response){
            //alert('ajax success: ' + $captcha_code.val());//debug statement
            if(Number(response)==='1'){//captcha correct
              captcha_verified = true;
              $captcha_code.attr('disabled',true);
              if(error_mesg.length===0){
                $form.get(0).submit();//Hooray, everything verified - submit the form.
              }
            }
            else{//captcha failed
              error_mesg.push("Image verification failed.");
              $captcha_code.parent().addClass('error');
              change_captcha();//change capture on failure, otherwise a clever bot could crack the captcha code with multiple attempts.
            }
          },
          error: function(){
            alert('ajax error: ' + $captcha_code.val());//debug statement
            error_mesg.push("Your image verification code may be correct but an error occurred while verifying it.");
          },
          complete: function(){
            alert('ajax complete: ' + $captcha_code.val());
            if(error_mesg.length > 0){
              alert(error_mesg.join("\n"));
            }
          }
        });
      }
    }
    return false;
  });
  
  function change_captcha(){
    document.getElementById('captcha').src="get_captcha.php?rnd=" + Math.random();
  }
  $('img#refresh').click(change_captcha);
});
</script>
</head>

<body>

<!--Snippets of HTML CODE-->
<form name="present_form" id="present_form" method="post" action="processForm.php">

<table width="100%" border="0" cellspacing="5" cellpadding="0">
  <tr>
    <td width="20%">Name</td>
	<td width="80%"><input name="name" type="text" id="name" size="30" /></td>
  </tr>
  <tr>
    <td>Tel</td>
    <td><input name="tel" type="text" id="tel" size="30" /></td>
  </tr>
</table>

<dl>Please enter the text that you see in the image into the box on below.</dl>

<table width="100%" border="0" cellspacing="5" cellpadding="0">
	<div id="wrap" align="center">
		<img src="get_captcha.php" alt="" id="captcha" />
		<br clear="all" />
		<input type="text" name="captcha_code" size="20" maxlength="6" />
		<!--input name="code" type="text" id="code"-->
	</div>
	<img src="refresh.jpg" width="25" alt="" id="refresh" />
</table>

<div class="btn">
   <input name="btn_submit" type="button" id="btn_submit" value="Submit" />
</div>

</form>

</body>
</html>

processForm.php

<?php
session_start();
require("include/application_top.php");

if(@$_REQUEST['captcha_code'] || @strtolower($_REQUEST['captcha_code']) == strtolower($_SESSION['random_number']))
	{
	
$table_fields = array("name", "tel");
$table_name = "testing";

$CHARSET_ENCODING="UTF-8";
$EMAIL_HEADER_EOL="\n";

mb_internal_encoding($CHARSET_ENCODING);

$standard_emailheaders="MIME-Version: 1.0".$EMAIL_HEADER_EOL;
$standard_emailheaders.="X-Mailer: PHP/".phpversion().$EMAIL_HEADER_EOL;
$standard_emailheaders.="Content-type: text/plain; charset=\"".$CHARSET_ENCODING."\"".$EMAIL_HEADER_EOL;
$standard_emailheaders.="Content-Transfer-Encoding: 8bit";


if(isset($_POST['name'])){
  
  $connection = mysql_connect (DB_SERVER, DB_USER, DB_PASS) or
	die ('I cannot connect to the database because: ' . mysql_error());
  mysql_select_db (DB_NAME, $connection);
  $query = "INSERT INTO .....";
  foreach ($table_fields as $field_name) {
      $http_var = $field_name;
	    $query .= ", $field_name='".mysql_real_escape_string($value)."'";
  }
  
  mysql_query ($query, $connection)
	or die(mysql_error()."\n<br />This is the query:\n<br />".$query);
  $notification_to="yourmailaddress@mail.com";
  $notification_subject=" Present Application Received";
  mail($notification_to, $notification_subject);
  
  header ("Location: thankyou.php");
	}
		
 }
	else
	{
    header('Location: checkForm.php?retry=yes');
	}

?>

verify_captcha.php

<?php
session_start();
require("include/application_top.php");
	
if(@$_REQUEST['captcha_code'] || @strtolower($_REQUEST['captcha_code']) == strtolower($_SESSION['random_number']))
	{
      // insert your name , email and text message to your table in db
		echo 1;// submitted 
	}
	else
	{
		echo 0; // invalid code
	}
	?>

get_captcha.php

<?php
session_start();

$string = '';

for ($i = 0; $i < 5; $i++) {
	$string .= chr(rand(97, 122));
}

$_SESSION['random_number'] = $string;

$dir = 'fonts/';

$image = imagecreatetruecolor(165, 50);

// random number 1 or 2
$num = rand(1,2);
if($num==1)
{
	$font = "Capture it 2.ttf"; // font style
}
else
{
	$font = "Molot.otf";// font style
}

// random number 1 or 2
$num2 = rand(1,2);
if($num2==1)
{
	$color = imagecolorallocate($image, 113, 193, 217);// color
}
else
{
	$color = imagecolorallocate($image, 163, 197, 82);// color
}

$white = imagecolorallocate($image, 255, 255, 255); // background color white
imagefilledrectangle($image,0,0,399,99,$white);

imagettftext ($image, 30, 0, 10, 40, $color, $dir.$font, $_SESSION['random_number']);

header("Content-type: image/png");
imagepng($image);

?>
0

It's entirely possible that my javascript still needs to be debugged, and maybe your php though on quick inspection, get_captcha.php and verify_captcha both look OK - nothing is obviously wrong.

Back in the javascript, try alerting verify_capture.php's response (at line 50 in checkForm.php):

alert('ajax success: ' + $captcha_code.val() + ': ' + response);//debug statement

If you also remove the @ error-suppressors from the php, then you should get some idea of where the process is failing.

Airshow

Edited by Airshow: n/a

0

It's entirely possible that my javascript still needs to be debugged, and maybe your php though on quick inspection, get_captcha.php and verify_captcha both look OK - nothing is obviously wrong.

Back in the javascript, try alerting verify_capture.php's response (at line 50 in checkForm.php):

alert('ajax success: ' + $captcha_code.val() + ': ' + response);//debug statement

If you also remove the @ error-suppressors from the php, then you should get some idea of where the process is failing.

Airshow

Hi Airshow, I did what you suggested and remove @ and uncommented out :

alert('ajax success: ' + $captcha_code.val() + ': ' + response);//debug statement

but it is still not working; whenever I entered the code correct or wrong it does not work...I am pulling my hair out here..

Any ideas?
PS: Your private msg is full? Can I send you PM please?

0

I just noticed, my javascript's if(!captcha_verified){...} needs an else clause, otherwise the form won't be submitted if the captcha is successfully entered before the rest of the form verifies:

if(!captcha_verified){
      ...
      ...
      ...
    }
    else {
      if(error_mesg.length===0){
        $form.get(0).submit();//Hooray, everything verified - submit the form.
      }
    }

If it still doesn't work, then start asking yourself questions, eg:

  • How far does it get? Insert alerts.
  • Does the success handler fire?
  • Does verify_captcha.php work when called directly from the browser's address bar? verify_captcha.php?captcha_code=ABCDE
  • What happens if you make verify_captcha.php's response unambiguously '1' or '0'?

These are typical debugging questions and precisely what I would be asking myself if I was doing the development. Code almost never works first time. It's very often a case of 10% effort to get yourself started and 90% testing/debugging. You will get quicker with practice.

Airshow

0

I just noticed, my javascript's if(!captcha_verified){...} needs an else clause, otherwise the form won't be submitted if the captcha is successfully entered before the rest of the form verifies:

if(!captcha_verified){
      ...
      ...
      ...
    }
    else {
      if(error_mesg.length===0){
        $form.get(0).submit();//Hooray, everything verified - submit the form.
      }
    }

If it still doesn't work, then start asking yourself questions, eg:

  • How far does it get? Insert alerts.
  • Does the success handler fire?
  • Does verify_captcha.php work when called directly from the browser's address bar? verify_captcha.php?captcha_code=ABCDE
  • What happens if you make verify_captcha.php's response unambiguously '1' or '0'?

These are typical debugging questions and precisely what I would be asking myself if I was doing the development. Code almost never works first time. It's very often a case of 10% effort to get yourself started and 90% testing/debugging. You will get quicker with practice.

Airshow

Hi Airshow,

Can you tell me how do I change this error checking into the format that you did please? As this include checkbox I am bit confused how I can do the way you did.

Thanks.

..
var $terms_agree = $("[name='terms_agree']");
..
..
 $('[name=terms_agree]').parent().css('color', '');
    if($('input:checkbox[name=terms_agree]:checked').val() == undefined){
      error_num++;
      error_mesg += "Please accept the terms and conditions。 \n";
      $('[name=terms_agree]').parent().css('color', 'red');
    }
..
..

I tried to change into this but it does not seem correct, any idea How?

..
var $terms_agree = $("[name='terms_agree']");
..
if($('input:checkbox[name=terms_agree]:checked').val() == undefined){
      error_mesg.push(""Please accept the terms and conditions");
      $terms_agree.parent().addClass('error');
    }
	else {
      $terms_agree.parent().removeClass('error');
    }
..
..

Still trying to do the "trail and error" no success so far but will keep you posted. Thanks.

Edited by siabenie: n/a

0

Airshow, I have put all the code together but now the problem is; when I clicked the button Submit without filling in the fields there is no error checking just nothing happen.....:icon_rolleyes:

You think I shall remove this code from the processForm.php?

if(@$_REQUEST['captcha_code'] || @strtolower($_REQUEST['captcha_code']) == strtolower($_SESSION['random_number']))
	{
..
..
	else
	{
    header('Location: checkForm.php?retry=yes');
	}
0

So try my second test idea - return the two captcha strings (concatenated with a space separator), so you can inspect them in the alert.

Does require("include/application_top.php"); put any output into the page, or is is just code? Try commenting the line out and see what happens.

A

Sorry I have full your mailbox :$

The require("include/application_top.php"); only contain a connection to DB, tables, and functions.

When I commented out the require("include/application_top.php"); session_start(); on the page verify_captcha.php and changed the exit('1'); .. exit('0'); in verify_captcha.php - Then entered a correct or incorrect code: I will show an alert 1,1 then redirect to thankyou.php

If I commented out just the the require("include/application_top.php"); leaving the session_start(); on the page verify_captcha.php I will get an error msg regardless code was entered correct or not.

If I commented out the alert on form (checkForm.php) and using the echo 1; .. echo 0; on the verify_captch.php it will redirect me to the thankyou.php page regardless the code I entered correct or not. Then if I changed the echo 1; .. echo 0; to exit('1'); .. exit('0'); then it will show me "Image verification failed" regardless the code I entered correct or not(with out without commented out the alert msg)

Maybe I do not need the require("include/application_top.php"); in verify_captcha.php?

I hope I am not confusing you here - so difficult to explain.

You mean this:

..
..
if(response==='1'){//captcha correct
..

into this:

..
..
if(response==='1'  + ' '){//captcha correct
..

PS: Please ignore the URL url: "verify_captcha02.php", it is 02 as I have made a second copy of it.

0

Hi Airshow,

How's your weekend? Mine been spending all bugging with the CAPTCHA - it is still not working...:( I tried almost everything but I guess must be smoething I missed!.

Can you please suggest me what is actually wrong? I have change from '1' to 1 and also the rest as I explained on my post to you but still no success:(:(

I'm looking forward to hearing from you.
Thanks.
S

0

Hi Airshow,

Here are the code: I think what went wrong is on the verify_captch.php but I am not exactly sure which part as I did tried to change and commented out few of them still no much luck.

Please have a look my the code. Thanks.

checkForm.php

<?php
session_start();
require("include/application_top.php");

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
<head>

<link rel="stylesheet" href="css/master.css" type="text/css" media="screen,tv,print" />
<link rel='stylesheet' type='text/css' href='css/navi.css' />
<link rel="stylesheet" href="jquery.superbox.css" type="text/css" media="all" />

<head>
<style type="text/css">
#superbox-overlay{
	background:#000000;
}
#superbox-container .loading{
	width:28px;
	height:28px;
	margin:0 auto;
	text-indent:-9999px;
	background:url(images/loader.png) no-repeat 0 0;
}
#superbox .close a{
	float:right;
	padding:0 5px;
	line-height:20px;
	cursor:pointer;
}
.style3 {
	color: #FF0000
}
input.error {
	border: 1px solid red;
}
input.pass {
	background-color: #98C098;
	font-weight: bold;
}
select.error {
	border-right: red 1px solid;
	border-top: red 1px solid;
	border-left: red 1px solid;
	border-bottom: red 1px solid;
	background-color: #fffffe;
}
textarea.error {
	border-right: red 1px solid;
	border-top: red 1px solid;
	border-left: red 1px solid;
	border-bottom: red 1px solid;
	background-color: #fffffe;
}
#formError {
	width: 300px;
	padding: 5px;
	border: 3px solid #FF0000;
}
#wrap{
	border:solid #CCCCCC 1px;
	width:203px;
	-webkit-border-radius: 10px;
	float:left;
	-moz-border-radius: 10px;
	border-radius: 10px;
	padding:3px;
	margin-top:3px;
	margin-left:80px;
}

img#refresh{
	float:left;
	margin-top:30px;
	margin-left:4px;
	cursor:pointer;
}
 

</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
	var $form  = $("[name='present_form']");
	var $tel   = $("[name='tel']");
	var $name  = $("[name='name']");
	var $email = $("[name='email']");
	var $terms_agree = $("[name='terms_agree']");
	
	var $captcha_code = $("[name='captcha_code']").html('');
	var captcha_verified = false;
	var $formError = $("#formError").hide();

	//****** start: debug vars *******
	//var captcha_sim;//for simulating captcha pass/fail
	var $msg1 = $("#msg1");
	//var $msg2 = $("#msg2");
	//var $msg3 = $("#msg3");
	//var $msg4 = $("#msg4");
	//****** end: debug vars *******
  
	function showErrorMesg(mesgArray){
		//alert(mesgArray.join("<br/>"));
		$formError.html(mesgArray.join("<br/>")).show();
	}
	function hideErrorMesg(){
		$formError.hide();
	}
	
	function validate_form() {
		var error_mesg = [];
		hideErrorMesg();

		if($name.val()===""){
			error_mesg.push("Please enter your name");
			$name.addClass('error');
		}
		else {
			$name.removeClass('error');
		}

		if($tel.val()==""){
			error_mesg.push("Please enter tel no");
			$tel.addClass('error');
		}
		else {
			$tel.removeClass('error');
		}

		if($email.val()==""){
			error_mesg.push("Please enter email");
			$email.addClass('error');
		}
		else {
			$email.removeClass('error');
		}
		
		if(!$terms_agree.attr('checked')){
		error_mesg.push("Please accept the terms and conditions");
		$terms_agree.addClass('error');
		}
		else {
		$terms_agree.removeClass('error');
		}

		if(!captcha_verified){
			if($captcha_code.val()===""){//user HAS NOT attempted the captcha
				error_mesg.push("Please enter the image verification");
				$captcha_code.addClass('error');
				showErrorMesg(error_mesg);
			}
			else{//user HAS attempted the captcha
				$captcha_code.removeClass('error');
				//$("#msg2").html(captcha_sim);//debug statement
				//$("#msg3").html();//debug statement
				$.ajax({
					//url: (captcha_sim===0) ? "verify_captcha_0.html" : "verify_captcha_1.html",
					url: "verify_captcha02.php",
					type: "POST",
					data: {code: $captcha_code.val()},
					success: function(response){
					//alert([response, response.length]);
						//$("#msg3").html('ajax success: ' + ' response: ' + response);//debug statement
						if(response==='1'){//captcha correct
							captcha_verified = true;//lock in the verified captcha
							$captcha_code.attr('disabled',true).addClass('pass');//lock in the verified captcha
							alert([response, response.length]);
						}
						else{//captcha failed
							error_mesg.push("Image verification failed.");
							$captcha_code.addClass('error');
							change_captcha();//change capture on failure, otherwise a clever bot could crack the captcha code with multiple attempts.
						}
					},
					error: function(){
						//alert('ajax error: ' + $captcha_code.val());//debug statement
						//error_mesg.push("Your image verification code may be correct but an error occurred while verifying it.");
						//alert([response, response.length]);
					},
					complete: function(){
						//$("#msg4").html('ajax complete');
						if(error_mesg.length===0){
							$form.get(0).submit();//Hooray, everything verified - submit the form.
						}
						else{
							showErrorMesg(error_mesg);
						}
					}
				});
			}
		}
		else{
			if(error_mesg.length===0){
				$form.get(0).submit();//Hooray, everything verified - submit the form.
			}
			else{
				showErrorMesg(error_mesg);
			}
		}
		return false;
	}
	
	$("[name='btn_submit']").click(validate_form);
	/*$("[name='btn_submit']").click(function(){
		captcha_sim = 0;
		$("#msg1").html(captcha_sim);
		validate_form();
	});*/
	/*$("[name='btn_submit_1']").click(function(){
		captcha_sim = 1;
		$("#msg1").html(captcha_sim);
		validate_form();
	});*/
  
	function change_captcha(){
		document.getElementById('captcha').src="get_captcha.php?rnd=" + Math.random();
	}
	$('img#refresh').click(change_captcha);
});
</script>
</head>

<body><a name="top" id="top"></a>

<div id="container">

<!---------------------- header ------------------------------------------------------------------------------>


<?php
require_once 'include/header.php';
?>

<!---------------------- navi------------------------------------------------------------------------------>

<?php
$page="presents";
require_once 'include/navi.php';
?>



<p class="crumbs"><a href="index.php"></a>/</p>

<div id="content" >

<h2 id="presents"></h2>

<!---------------------- left------------------------------------------------------------------------------>

<div id="presentsleft">
</div><!-- #pluscardleft end -->
<!---------------------- right------------------------------------------------------------------------------>

<div id="presentsright">

			<div id="formError"></div>
			<div id="form">
			<form name="present_form" method="post" action="processForm.php">
<h4></h4>

<div id="formwhite">

<table width="100%" border="0" cellspacing="5" cellpadding="0">
  <tr>
    <td width="20%">Name</td>
	<td width="80%"><input name="name" type="text" id="name" size="30" /></td>
  </tr>
  <tr>
    <td>Tel</td>
    <td><input name="tel" type="text" id="tel" size="30" /></td>
  </tr>
  <tr>
    <td>E-mail</td>
    <td><input name="email" type="text" id="email" size="30" /></td>
  </tr>
</table>

<p><input type="checkbox" name="terms_agree" id="terms_agree" value="y" /> Terms and conditions。</p>

					<dl>Please enter the text that you see in the image into the box on below.</dl>
					
					<table width="100%" border="0" cellspacing="5" cellpadding="0">

					<div id="wrap" align="center">
						<img src="get_captcha.php" alt="" id="captcha" />
						
						<br clear="all" />
						<input type="text" name="captcha_code" id="captcha_code"" size="20" maxlength="6" />
					
					</div>
					
					<img src="refresh.jpg" width="25" alt="" id="refresh" />
					</table>
									
					<p>&nbsp;</p>


<div class="btn"><input name="btn_submit" type="button" id="btn_submit" value="Submit" />
</div>
</div>
</form>
</div>
 

<div id="allpresent">
<br /><br />

</div>
..
</div><!-- #presentsright end -->


<p class="toplink"><a href=""></a></p>

<div class="clear"></div>
</div>
</div>
<div id="msg1"></div>
<!--div id="msg2"></div>
<div id="msg3"></div>
<div id="msg4"></div-->

<?php
require_once 'include/footer.php';
?>
</body>
</html>

processForm.php

<?php
session_start();
require("include/application_top.php");

$table_fields = array("name", "tel", "email");
$table_name = "present";

$form_num = 1;
if(isset($_GET['form_num']) && $_GET['form_num']==2){
  $form_num = 2;//$_GET['form_num'];
}
mb_internal_encoding($CHARSET_ENCODING);

$standard_emailheaders="MIME-Version: 1.0".$EMAIL_HEADER_EOL;
$standard_emailheaders.="X-Mailer: PHP/".phpversion().$EMAIL_HEADER_EOL;
$standard_emailheaders.="Content-type: text/plain; charset=\"".$CHARSET_ENCODING."\"".$EMAIL_HEADER_EOL;
$standard_emailheaders.="Content-Transfer-Encoding: 8bit";


if(isset($_POST['name'])){
  
  $connection = mysql_connect (DB_SERVER, DB_USER, DB_PASS) or
	die ('I cannot connect to the database because: ' . mysql_error());
  mysql_select_db (DB_NAME, $connection);
  $query = "INSERT INTO `$table_name` SET time_added=NOW(), form_num=$form_num";
  foreach ($table_fields as $field_name) {
      $http_var = $field_name;
      $http_val = (isset($_POST[$http_var]) ? httpreqvar_strip($_POST[$http_var]) : "");
      $value = $http_val;
 
  }
  
  mysql_query ($query, $connection)
	or die(mysql_error()."\n<br />This is the query:\n<br />".$query);

 ...
 ...
  mail($notification_to, $notification_subject, $notification_body, $notification_headers);
  
  header ("Location: thankyou.php");
  
}
?>

verify_captcha.php

<?php
//session_start();
//require("include/application_top.php");
	
if($_REQUEST['captcha_code'] || strtolower($_REQUEST['captcha_code']) == strtolower($_SESSION['random_number']))
	{
      // insert your name , email and text message to your table in db
	  //header('Location: processForm.php');
	  //echo 1;// submitted  
	  //response==='1';
	  exit('1');//pass
	  //echo strtolower($_REQUEST['captcha_code']);
	}
	else
	{
	    //header('Location: checkForm2.php');
		//echo 0; // invalid code
		exit('0');//fail
		//response==='0';
	}
	?>
0

Siabenie,

I have spotted something:

//--find
data: {code: $captcha_code.val()},
//--replace with
data: {captcha_code: $captcha_code.val()},

Hopefully that will bring things to life.

Airshow

0

Siabenie,

I have spotted something:

//--find
data: {code: $captcha_code.val()},
//--replace with
data: {captcha_code: $captcha_code.val()},

Hopefully that will bring things to life.

Airshow

Hi Airshow,

I have changed the code as you suggested and yes the alert show 1, 1:

..
..
url: "verify_captcha.php",
type: "POST",
data: {captcha_code: $captcha_code.val()},
success: function(response){
..
..

..but the problem is:

When I entered a wrong code - the form still proceed to the thankyou page. When I entered a correct code the form still going to thankyou page. It does not seem validate the code as we wanted?

Here is my verify_captcha.php

<?php
session_start();
//require("include/application_top.php");
	
if($_REQUEST['captcha_code'] || strtolower($_REQUEST['captcha_code']) == strtolower($_SESSION['random_number']))
	{
      // insert your name , email and text message to your table in db
	  //header('Location: processForm.php');
	  //echo 1;// submitted  
	  //response==='1';
	  exit('1');//pass
	  //echo strtolower($_REQUEST['captcha_code']);
	}
	else
	{
	    //header('Location: checkForm2.php');
		//echo 0; // invalid code
		exit('0');//fail
		//response==='0';
	}
	?>

Any idea we have missing?

0

I think that's due to your validation test.

In verify_captcha.php:

//change
if($_REQUEST['captcha_code'] || strtolower($_REQUEST['captcha_code']) == strtolower($_SESSION['random_number']))
//to
if(strtolower($_REQUEST['captcha_code']) == strtolower($_SESSION['random_number']))

Airshow

Edited by Airshow: n/a

0

You can now reduce verify_captcha.php down to:

<?php
session_start();

if(strtolower($_REQUEST['captcha_code']) == strtolower($_SESSION['random_number']))
{
	exit('1');//pass
}
else
{
	exit('0');//fail
}
?>

And please remember that this is really only a pre-verification check. You have to reverify the captcha right at the top of processForm.php, otherwise that script would be accessible without verification.

If the test in processForm.php fails, then redirect back to checkForm.php . This won't happen to bona fide users; only hackers who did not use checkForm.php will be redirected.

Airshow

0

I think that's due to your validation test.

In verify_captcha.php:

//change
if($_REQUEST['captcha_code'] || strtolower($_REQUEST['captcha_code']) == strtolower($_SESSION['random_number']))
//to
if(strtolower($_REQUEST['captcha_code']) == strtolower($_SESSION['random_number']))

Airshow

Hi Airshow,

Great yes that seems do the job!! I will try again to make sure it does run fine. But thanks so far so good!

One question though; How can I pop up all error messages? e.g. this error message:

..
if($name.val()===""){
error_mesg.push("Please enter your name");
$name.addClass('error');
		}
else 
{
   $name.removeClass('error');
}

I want it pop up error message, I tried this:

..
alert.error_mesg.push("Please enter your name");
..

but it does not work. Perhaps the way I coded them wrong, any idea?

Edited by siabenie: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.