简体   繁体   中英

imagepng($image);captcha and session variables

I have the following code:

<?php session_name('mysession');
session_start();
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test Captcha</title>
</head>

<body>

Captcha Image:
<img src="get_captcha.php" width="139" height="139" />
<?php 
echo 'Captcha text:'.$_SESSION['random_number']
 ?>
</body>
</html>

and get_captcha.php is:

<?php
session_name('mysession');
session_start();
$string = '';

for ($i = 0; $i < 5; $i++) {
    $string .= chr(rand(97, 122));
}

$_SESSION['random_number'] = $string;

$dir = 'fonts/';

$image = imagecreatetruecolor(165, 50);

// random number 1 or 2
$num = rand(1,2);
if($num==1)
{
    $font = "Capture it 2.ttf"; // font style
}
else
{
    $font = "Molot.otf";// font style
}

// random number 1 or 2
$num2 = rand(1,2);
if($num2==1)
{
    $color = imagecolorallocate($image, 113, 193, 217);// color
}
else
{
    $color = imagecolorallocate($image, 163, 197, 82);// color
}

$white = imagecolorallocate($image, 255, 255, 255); // background color white
imagefilledrectangle($image,0,0,399,99,$white);

imagettftext ($image, 30, 0, 10, 40, $color, $dir.$font, $_SESSION['random_number']);


imagepng($image);

?>

The problem is that when I run first time the test-captcha.php I get the following error: Undefined index: random_number in test-captcha.php on line 17 ($_SESSION['random_number'] is not set!!!!)

After refreshing the page the $_SESSION['random_number'] displays the previous captcha text! Does anybody have any ideas why this happens??????

Because of first time session have empty. so first time you have to set any value to session.

<?php 
if(isset($_SESSION['random_number']))
{
    echo 'Captcha text:'.$_SESSION['random_number']
}
else{
    $_SESSION['random_number']='any data';   
}
?>

Something like that you want.
Try it.

$string = '';

for ($i = 0; $i < 5; $i++) {

 $string .= chr(rand(97, 122)); 

}

$_SESSION['random_number'] = $string;

Write this code in your html page not in get_captcha.php. It works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM