[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Check captcha in javascript

Posted on 2011-05-02
10
Medium Priority
?
775 Views
Last Modified: 2012-05-11
Hi,

The following PHP code I use to check is a captacha is entered correctly.
function checkcaptcha() {
			session_start();
			if ($_SESSION["pass"] != $_POST["userpass"]) {
                errorMsg .= "\n  Incorrect validation captcha.";
				return 1;
			}
   }

Open in new window


if ($dontsendemail == 0) $dontsendemail = checkcaptcha();

Open in new window


I've tried to pre-check the captcha within javascript, but had no luck till now.
<script language="JavaScript" type="text/javascript">
<!--
//Controleer of het formulier correct is ingevuld.
function CheckForm () { 
	// Initialise variables
	var errorMsg = "";
	// Controle op het veld Naam
	session_start();
	if (($_SESSION["pass"] != document.captcha_form.userpass.value){
		errorMsg += "\n  Afbeeldingtekst \t\t-     De tekst van de afbeelding is niet correct ingevoerd (hoofdletter gevoelig)";	
	}
	// Toon melding bij foutieve/onvolledige invoer
	if (errorMsg != ""){
		msg =  "Uw vraag kan niet verstuurt worden omdat niet alle verplichte\n";
		msg += "velden (correct) ingevuld zijn.\n";
		msg += "\n";
		msg += "De volgende velden dienen gecorrigeerd te worden:\n";
		errorMsg += alert(msg + errorMsg + "\n\n");
		return false;
	}
	return true;
}
// -->
</script>

Open in new window


Any suggestions?
0
Comment
Question by:Stef Merlijn
  • 5
  • 4
10 Comments
 
LVL 15

Expert Comment

by:ludofulop
ID: 35503230
you are messing up php and javascript - you can not use php functions in javascript, and vice versa.
0
 

Author Comment

by:Stef Merlijn
ID: 35503251
Yes, but how to do it anyway with correct code?
0
 
LVL 15

Expert Comment

by:ludofulop
ID: 35503290
you can use AJAX to send entered value to PHP script, which compares it and returns true/false answer. But this is assynchorouns call, so another function is returning the result, than called function (so it can not be directly used in 'onsubmit' handler).

Anyway, you have to check the captcha also after submitting, so i don't know if there is a reason to check it using javascript. Your captcha get's weaker for breaking it (as robot doesn't need to process the image, just to process the results of ajax handler call.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:Stef Merlijn
ID: 35503381
I want to check the captcha with Java first.
But in case java is disabled, I'll do the same check in PHP.
0
 
LVL 15

Expert Comment

by:ludofulop
ID: 35503476
that's really not a good idea.
0
 

Author Comment

by:Stef Merlijn
ID: 35503546
Some seraching on the internet told me that checking the captcha with java is not a good idea.
So how would this go with AJAX?
Will that work for all visitors?
Is there any additional installation needed in order to run AJAX script?
0
 

Author Comment

by:Stef Merlijn
ID: 35503570
What also would be perfect is when the PHP-script down't create a whole new page with only the errormessage, but that it would create a smapp popup containing the errormessage.

function checkcaptcha() {
                        session_start();
                        if ($_SESSION["pass"] != $_POST["userpass"]) {

                          /* replace this line with some code to show a popup */
                           die("Incorrect validation captcha.");

                        }
   }

Open in new window

0
 
LVL 15

Expert Comment

by:ludofulop
ID: 35503574
Using ajax is almost the same issue, as this is also partially a javascript solution.
Anyway, check out the ajax tutorial for example here: http://www.xul.fr/en-xml-ajax.html

To easily explain differences between _php only_ and _ajax_ solutions, from the robots point of view:

1/ when using php only solution, each request to a script generates a new captcha image. Robot has always only one chance to parse the image a get correct value

2/ when using ajax solution, image is generated only once, and then you can make unlimited background calls to a PHP handler (which compares captcha value and entered value, and return true/false). Robot can make unlimited request directly to PHP handler, so using brute-force method, can break any captcha image that you generate.

I recommend to use php only solution.
0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 35504200
It is technically incompetent to check a captcha in any client-side programming because captcha is designed to be tested on the server side, after the form is submitted.  A check on the client side is meaningless from a security standpoint because the client can simply bypass the check!

Here is a simple script that implements a CAPTCHA test.  It comes in three parts (form, image generator, and test script) and while in theory, it should be easy to orchestrate a rainbow attack against it, in practice I have used it successfully many times.

Best regards, ~Ray
<?php // RAY_captcha_in_action.php
error_reporting(E_ALL);

// IF ANYTHING WAS POSTED
if (!empty($_POST))
{
    // TEST THE STRINGS
    if ($_POST["_newMd5"] != md5($_POST["_newCode"]))
    {
        // MIGHT WANT TO MAKE THIS USER-FRIENDLY
        echo 'SECURITY CODE NUMBER DID NOT MATCH';
    }
    else
    {
        echo "SUCCESS!";
    }
}
// END OF PHP - PUT UP THE FORM
?>
<form method="post">
<!-- STYLE THIS TO SUIT YOUR PAGE STYLE -->
Type <img style="display:inline;" src="RAY_captcha_image.php?dt=<?php $x = mt_rand(1000,10000); echo base64_encode($x); ?>" /> here:
<input name="_newCode" type="text"   maxlength="64" size="6" autocomplete="off" />
<input name="_newMd5"  type="hidden" value="<?php echo md5($x); ?>" />
<input type="submit" />
</form>

Open in new window

<?php // RAY_captcha_image.php
error_reporting(E_ALL ^ E_NOTICE);


// GENERATES A PICTURE OF A NUMBER INTO THE BROWSER OUTPUT


// DECODE THE INCOMING STRING
$data = base64_decode($_GET['dt']);

// CREATE AN IMAGE RESOURCE - CHOOSE THE SIZE THAT BEST MATCHES YOUR PAGE STYLE
$im = imagecreate(46,13);

// WHITE BACKGROUND
$bg = imagecolorallocate($im, 255,255,255);

// GRAY STRIPES
$gray = imagecolorallocate($im, 188,188,188);

// FIREBRICK TEXT
$text = imagecolorallocate($im, 178,34,34);

// ADD THE NUMBER TO THE IMAGE
imagestring($im,5,4,0,$data,$text);

// WRITE A GRAY STRIPE (OR MORE IF YOU CHOOSE)
imageline($im,4,12,38,0,$gray);

// SEND THE IMAGE INTO THE BROWSER OUTPUT STREAM
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);

Open in new window

0
 

Author Closing Comment

by:Stef Merlijn
ID: 35719176
Thank you all.
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
The title says it all. Writing any type of PHP Application or API code that provides high throughput, while under a heavy load, seems to be an arcane art form (Black Magic). This article aims to provide some general guidelines for producing this typ…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
Suggested Courses
Course of the Month20 days, 2 hours left to enroll

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question