0

I want to get the session captcha value in the onsubmit event of the form , so if the text entered is different of the session captcha data then I will cancel form submission. The problem is that I cannot get the session captcha value on document ready :

file of the captcha generation is named securitecode.php :

<?php
session_start();

$largeur  = 120;
$hauteur  = 40;
$longueur = 5;
$liste = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$code    = '';
$counter = 0;

$image = @imagecreate($largeur, $hauteur) or die('Impossible d\'initializer GD')
;

for( $i=0; $i<10; $i++ ) {
   imageline($image,
   mt_rand(0,$largeur), mt_rand(0,$hauteur),
   mt_rand(0,$largeur), mt_rand(0,$hauteur),
   imagecolorallocate($image, mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)
));
 }

for( $i=0, $x=0; $i<$longueur; $i++ ) {
   $charactere = substr($liste, rand(0, strlen($liste)-1), 1);
   $x += 10 + mt_rand(0,10);
   imagechar($image, mt_rand(3,5), $x, mt_rand(5,20), $charactere,
   imagecolorallocate($image, mt_rand(0,155), mt_rand(0,155), mt_rand(0,155)));
   $code .= $charactere;
 }

  header('Content-Type: image/jpeg');
  imagejpeg($image);
  imagedestroy($image);

  $_SESSION['securecode'] = $code;
?>

In my web page I create the image captcha :

...
<img id="captcha_img" src="securitecode.php" />
<input type="text" id="captcha" />
<span id="msg_captcha"></span>
...
<script type="text/javascript">
$(document).ready(function() {
    $('#msg_captcha').html("<?php echo $_SESSION['securecode']; ?>");
});
</script>

When the page loads for the first time there is nothing displayed inside the #msg_captcha span ! So how to get the captcha session data ?

pheromix
  • 18,213
  • 29
  • 88
  • 158

2 Answers2

3

This is because of the way sessions work.

Session values is available when a session is over and the session data has been written to the session file.

When requesting the page, you actually try to obtain a session value that hasn't yet been set for two reasons.

  1. The captcha image is loaded AFTER your initial request, but PHP has already handled the <?php echo $_SESSION['securecode']; ?> part.

  2. The $_SESSION['securecode'] value is written after the image has been loaded.

So basically, your solution is trying to read values too early.

The solution?

Check the captcha code with AJAX or verify the captcha code on the next request.

Repox
  • 15,015
  • 8
  • 54
  • 79
0

Javascript can't run PHP that way. PHP is a server side language, javascript is client side. Maybe this topic can help you.

Community
  • 1
  • 1