1

次のコードがあります。

<?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>

get_captcha.php は次のとおりです。

<?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);

?>

問題は、test-captcha.php を初めて実行したときに次のエラーが発生することです: Undefined index: random_number in test-captcha.php on line 17 ($_SESSION['random_number'] is not set!!!!)

ページを更新した後、$_SESSION['random_number'] は以前のキャプチャ テキストを表示します! なぜこれが起こるのか誰にも考えがありますか??????

4

2 に答える 2

0

$string = '';

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

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

}

$_SESSION['random_number'] = $string;

get_captcha.php ではなく、HTML ページにこのコードを記述します。それは正常に動作します。

于 2012-11-17T09:16:03.930 に答える
0

初めてのセッションのため、空があります。したがって、初めてセッションに値を設定する必要があります。

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

あなたが望むようなもの。
それを試してみてください。

于 2012-11-17T09:01:54.480 に答える