送信する前にjQueryで検証されるフォームに取り組んでいます。フィールドの1つはキャプチャです。
アイデアは非常に単純で、キャプチャは画像として表示され、非表示のフィールドにも保存されます。ユーザーが入力フィールドにキャプチャを入力するとき、それは非表示のフィールドの値と等しくなければなりません。これは私が持っているjQueryコードです。
<script>
$(document).ready(function(){
$("#register").validate({
errorElement: 'div', ignore: 'hidden',
rules: {
password: {
required: true
},
password2: {
required: true, equalTo: "#password"
},
agree: {
required: true
},
captcha: {
required: true, equalTo: "#captcha2"
}
},
messages: {
password2: "Please repeat the same password",
captcha: "The captcha you entered is wrong",
agree: "You have to be at least 16 years old and agree to the terms of service"
}
});
});
</script>
フォームのhtmlコードはさらに単純ですが、その一部のみを示します。
<p>
<img src='/includes/captcha.php' />
</p>
<p>
<label for="Captcha">Captcha</label>
<em> *</em><input type="text" name="captcha" id="captcha" size="25"
class="require" minlength="5" />
<input type="hidden" name="captcha2" id="captcha2"
value="<?php echo $_SESSION['captcha'];?>" />
<?php echo $_SESSION['captcha']; ?>
ここに奇妙なことがあります。session ['captcha']をエコーすると、非表示フィールドの値とは異なる値が取得されます。エコーすると、前のキャプチャが表示されます。
したがって、キャプチャ値がABCであるとしましょう。ページを更新すると、captcha+hiddenフィールドがDEFに変わります。しかし、session ['captcha']をエコーすると、まだABCが表示されます。
なぜこうなった?
これがcaptcha.phpファイルのコードです。
<?php
session_start();
header("Content-type: image/png");
$string = '';
for ($i = 0; $i < 5; $i++) {
// this numbers refer to numbers of the ascii table (lower case)
$string .= chr(rand(97, 122));
}
$_SESSION['captcha'] = $string;
putenv('GDFONTPATH=' . realpath('.'));
$dir = 'musicals';
$image = imagecreatetruecolor(170, 60);
$black = imagecolorallocate($image, 0, 0, 0);
$color = imagecolorallocate($image, 129, 180, 79); // green
$white = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image,0,0,399,99,$white);
imagettftext ($image, 30, 0, 10, 40, $color, $dir, $_SESSION['captcha']);
imagepng($image);
?>