Menu principale:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Captcha Example</title> </head> <body> <form action="submit.php" method="post"> <label>First Name <input type="text" name="firstName" /></label><br> <label>Last Name <input type="text" name="lastName" /></label><br> <label>Message <textarea name="message"></textarea></label><br> <input type="submit" name="submit"> </form> </body> </html>
<?php //creazione dell'immagine e aggiunta di un background di colore grigio $image = imagecreatetruecolor(120, 30); $background = imagecolorallocate($image, 200, 200, 200); imagefill($image, 0, 0, $background);
$linesColor = imagecolorallocate($image, 100, 100, 100); for ($i=1; $i<=5; $i++) { imagesetthickness($image, rand(1,2)); imageline($image, 0, rand(0,30), 120, rand(0,30), $linesColor); }
$captcha = ''; $textColor = imagecolorallocate($image, 0, 0, 0); for ($x = 15; $x <= 95; $x += 20) { $value = rand(0, 9); imagechar($image, rand(3, 5), $x, rand(2, 14), $value, $textColor); $captcha .= $value; }
header('Content-type: image/png'); imagepng($image); imagedestroy($image);
<p><img src="./captcha.php" /></p> <label>CAPTCHA <input type="text" name="captcha" /><br><br>
<?php session_start();
$_SESSION['captcha'] = $captcha;
<?php session_start(); //se accediamo al file senza eseguire il submit della form if (!isset($_POST['submit'])) { die('I dati non sono validi'); } if ($_POST['captcha'] != $_SESSION['captcha']) { die('Codice non valido'); } echo 'Codice valido.';