使用$ _SESSION php将页面之间的变量传递给麻烦

时间:2011-11-04 14:46:58

标签: php session

我正在为学校做作业,我们要制作两个php文件。第一个文件调用会话,生成随机的5个字符串,并将字符串保存到会话数组。第二个脚本生成一个图像,并从第一个文件中获取字符串并将其合并到图像上以制作验证码。

我在将值传递给第二个脚本时遇到问题。会话变量'captcha_string'在第一个脚本中完全可见,但不会传递给第二个页面。我是全新的,并且很沮丧。我的理解是,只要我开始会话,整个$ _SESSION数组应该可用。当我运行第一个脚本时,我得到一个破损的图像标记,而不是我希望的验证码。希望这能解决我的问题。

这是我为第一个文件所做的:

    <?php
   session_start();
   $possible_chars = array_merge(range('A','Z'),range('0','9'));
   shuffle($possible_chars); 
   $string = substr(implode($possible_chars),0,5);
   $_SESSION['captcha_string']=$string;

?>

<img src="captcha_generator.php" alt="Weinerdog!" />

这是第二个文件中的位,我尝试抓取$ string(captcha_string),名为“captcha_generator.php:

<?php
session_start();

putenv('GDFONTPATH=' . realpath('.')); 
header("Content-type: image/png");

//import string for the captcha from $_SESSION
$string = $_SESSION['captcha_string'];

// Build an image resource using an existing image as a starting point.
$backgroundimage = "captcha_wiener.jpg"; 
$im=imagecreatefromjpeg($backgroundimage); 
$colour = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));

// Output the string of characters using a true type font. 
// Above we set the font path to the current directory, this
// means that arial.ttf font file must be in this directory.
$font = 'arial.ttf'; 
$angle = rand(-5,5); 
imagettftext($im, 120, $angle, 50, 250, $colour, $font, $string);

// Draw some annoying lines across the image. 
imagesetthickness($im, 10); 
for ($i = 0; $i <3; $i++) { 
    imageline($im, rand(100,50), rand(150,200), rand(450,550), rand(200,250), $colour);
} 

// Output the image as a PNG and the free the used memory. 
imagejpeg($im); 
imagedestroy($im); 

?>

这当然是严格的练习,以确保我们可以使用会话传递值。使用验证码的其余代码没有问题,它已经过测试和运行。

1 个答案:

答案 0 :(得分:1)

你回放了一些内容类型设置为image / png的值,因此要么你已经发送了标题错误,要么就是没有发送文本(因为PHP缓存了) ),你将有一个破碎的图像,你将无法看到文本。

别担心,包括我在内的所有人都遇到过: - )