Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

implementing captcha?

Status
Not open for further replies.

rahulpatel

Programmer
Jan 20, 2007
33
AU
On my form I have a textbox and a button. The textbox searches my database and returns a true or false value.(Yes it is in the database or No it's not) This works well. The button is a button and not submit. There is an 'onclick' value which uses another page to do the searching and returns the value via ajax. However, I want to add a bit of security with captcha but every demo and tutorial I've found uses the button as submit.
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
    <title>.: Registrations :.</title>
  <script type="text/javascript">
        var url = "GetCustomerData.php?id="; // The server-side script
	   function handleHttpResponse() {	
		if (http.readyState == 4) {
			  if(http.status==200) {
			  	var results=http.responseText;
			  document.getElementById('divCustomerInfo').innerHTML = results;
			  }
  			}
		}
		
	    function requestCustomerInfo() {      
            var sId = document.getElementById("txtCustomerId").value;
			http.open("GET", url + escape(sId), true);
			http.onreadystatechange = handleHttpResponse;
			http.send(null);
        }
function getHTTPObject() {
  var xmlhttp;
 
  if(window.XMLHttpRequest){
    xmlhttp = new XMLHttpRequest();
  }
  else if (window.ActiveXObject){
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    if (!xmlhttp){
        xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    
}
  return xmlhttp;  
}
var http = getHTTPObject(); // We create the HTTP Object
</script>

<link href="rego.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="search">
  <form>
    <p>
      <input type="text" id="txtCustomerId" value="" /> 
      <input type="button" value="Search" onClick="requestCustomerInfo()" />
    </p>
    <div id="divCustomerInfo"></div>
    </form></div>
<div id="title"> </div>
</body>
</html>

This is the page that retrieves the data..
Code:
<?php
	
    //customer ID
    $sID = $_GET["id"];
    
    //variable to hold customer info
    $sInfo = "";
	$sInfo1 = "<a href=login.php>Log in</a> or <a href=register.php>register</a> for more information";
      
  $sDBServer = "localhost";
  $sDBName = "XXXX";
  $sDBUsername = "######";
  $sDBPassword = "######";
  $sQuery = "select * from number where number = ".$sID;

  $oLink = mysql_connect($sDBServer,$sDBUsername,$sDBPassword);
  @mysql_select_db($sDBName) or $sInfo="Unable to open database";
    //create the SQL query string
             
   if ($sID == "")
  {
  echo "<h4>Please enter a value.</h4>";
  exit;
  }
        
    if($sInfo == '') {
        if($oResult = mysql_query($sQuery) and mysql_num_rows($oResult) > 0) {
            $aValues = mysql_fetch_array($oResult,MYSQL_ASSOC);
			 $sInfo = "Number is registered<br />"."$sInfo1";
        } else {
            $sInfo = "Number is not registered.";
        }
    }	
    mysql_close($oLink);

?>
</head>
<body>
    <div id="divInfoToReturn"> <?php echo $sInfo ?> </div>
</body>
</html>

If it looks familiar, yes I'm learning from a book. This works fine but I have no idea where to add my captcha box and how to make it work from the button I already have on the form as most tutorials have submit buttons.

Any ideas where to head would be gratefully accepted.
 
use the requestCustomerInfo() application to grab the entry in the captcha box and submit it, with the search string, to the php server.

so if the captcha test is in a text field called 'captcha' (and with the same id) the relevant line would be

Code:
http.open("GET", url + escape(sId)+"&captcha=" + document.getElementById('captcha').value, true);

then, obviously, check the captcha value in your processing script before returning the answer.

Code:
 //customer ID
    $sID = $_GET["id"];
 $captcha = empty($_GET['captcha']) ? NULL : trim($_GET['captcha']);
 if (!testCaptcha($captcha)){
   echo "naughty, naughty";
   die();
 }

 function testCaptcha($captcha){
  if (empty($captcha)) return false;
  if (!isset($_SESSION['captcha'])) return false;
  if (empty($_SESSION['captcha'])) return false;
  if ($_SESSION['captcha'] === $captcha) {
    return true;
  } else {
    return false;
  }
}
 
Thanks for that. I added my captcha generation page to my form:

Code:
<div id="search">
  <form>
    <p>
      <input type="text" id="txtCustomerId" value="" />
      <input type="text" name="captcha" id="captcha"><img src="randomImage.php">
      <input type="button" value="Search" onClick="requestCustomerInfo()" />
    </p>
    <div id="divCustomerInfo"></div>
    </form></div>

However I still get the 'naughty, naughty' comment even though the text is correct in the box. How does the randomimage page pass the random number to the session to be tested? Am I missing more than I realise.?
 
the randomImage.php script should set a session variable. something like this

Code:
<?php
session_start();
$_SESSION['captcha'] = 'the captcha text';
//output the captcha image with headers
?>

of course the receiving script for the form also needs to start the session. modify the testCaptch() function like this

Code:
 function testCaptcha($captcha){
  [red]if(empty(session_id())) session_start();[/red]
  if (empty($captcha)) return false;
  if (!isset($_SESSION['captcha'])) return false;
  if (empty($_SESSION['captcha'])) return false;
  if ($_SESSION['captcha'] === $captcha) {
    return true;
  } else {
    return false;
  }
}
 
Mmmmmm, that red line of code is returning this error

Code:
Fatal error: Can't use function return value in write context
 
oh well. i'd forgotten that bug in the empty() function...

try
Code:
if (session_id() === '') session_start();
 
before people jump on me, the word bug above should have been in quotation marks. I acknowledge that the behaviour of empty() is documented but I submit that it is illogical (even though it is a language construct and not a function). In particular the error message confuses things mightily as, of course, the code is not being used in a write context.

 
jpadie, thanks for your help. Unfortunately I still get the error, so I scrapped what I was doing and found another tutorial (?easier to understand to me?) and re-wrote the page. This time it doesn't reference another page.

Code:
<?php
// we must never forget to start the session
session_start();

$errorMessage = '';
$successMessage = '';

if (isset($_POST['txtUserId'])) {
	// first check if the number submitted is correct
	$number   = $_POST['txtNumber'];
	
	if (md5($number) == $_SESSION['image_random_value']) {
		include 'library/config.php';
		include 'library/opendb.php';
		
		$userId   = $_POST['txtUserId'];
		
		// check if the user id and password combination exist in database
		$sql = "SELECT * 
				FROM member
				WHERE member = '$userId' ";
		
		$result = mysql_query($sql) or die('Query failed. ' . mysql_error()); 
		
		if (mysql_num_rows($result) == 1) {
			// the user id and password match, 
			// set the session
			$_SESSION['image_is_logged_in'] = true; 
			$successMessage="Member is registered<br /><a href=login.php>Log in</a> or <a href=register.php>register</a> for more information";
			// remove the random value from session			
			$_SESSION['image_random_value'] = '';
			
			// after login we move to the main page

		} else {
			$errorMessage = 'Member is not registered.';
		}
		
		include 'library/closedb.php';
	} else {
		$errorMessage = 'Sorry, wrong number. Please try again';
	}	
//}
?>
<html>
<head>
<title>Basic Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
if ($errorMessage != '') 
if ($successMessage !='')
?>
<?php
}
?>
<form action="" method="post" name="frmLogin" id="frmLogin">
  <table width="500" border="0" align="center" cellpadding="2" cellspacing="2">
    <tr>
      <td width="150">Serial Number</td>
      <td><input name="txtUserId" type="text" id="txtUserId"></td>
    </tr>
    <tr>
      <td width="150">Security Number</td>
      <td><input name="txtNumber" type="text" id="txtNumber" value="">
        &nbsp;&nbsp;<img src="randomImage2.php"></td>
    </tr>
    <tr>
      <td width="150">&nbsp;</td>
      <td><input name="btnLogin" type="submit" id="btnLogin" value="Login"></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><p align="left"><strong><font color="#990000"><?php echo $errorMessage; ?></font></strong> <strong><font color="#990000"><?php echo $successMessage; ?></font></strong></p></td>
    </tr>
  </table>
</form>
</body>
</html>

So thanks again for your help. Now all I need to do is AJAX the messages into the page. See you in the AJAX forum...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top