php - session 与图像 PHP 不匹配

标签 php session

我想知道为什么此脚本生成的图像中的字符与为 session 设置的字符不匹配。我找不到为什么会这样,如果有人可以提供帮助,那就太好了。谢谢,莉亚。

// Font directory + font name
$font = 'wordpress/wp-content/themes/boldy/fonts/SF Juggernaut Bold.ttf';
// Total number of lines
$lineCount = 20;
// Size of the font
$fontSize = 19;
// Height of the image
$height = 38;
// Width of the image
$width = 120;
$img_handle = imagecreate ($width, $height) or die ("Cannot Create image");
// Set the Background Color RGB
$backColor = imagecolorallocate($img_handle, 242, 242, 242);
// Set the Line Color RGB
$lineColor = imagecolorallocate($img_handle, 207, 207, 207);
// Set the Text Color RGB
$txtColor = imagecolorallocate($img_handle, 95, 95, 95);

// Generate
$string = "bcdefghijklmopqrstwxyz023456789";
for($i=0;$i<6;$i++){
    $pos = rand(0,36);
    $str .= $string{$pos};
}

$textbox = imagettfbbox($fontSize, 0, $font, $str) or die('Error in imagettfbbox function');

$x = ($width - $textbox[4])/2;
$y = ($height - $textbox[5])/2;

imagettftext($img_handle, $fontSize, 0, $x, $y, $txtColor, $font , $str) or die('Error in imagettftext function');

for($i=0;$i<$lineCount;$i++){
    $x1 = rand(0,$width);$x2 = rand(0,$width);
    $y1 = rand(0,$width);$y2 = rand(0,$width);
    imageline($img_handle,$x1,$y1,$x2,$y2,$lineColor);
}

header('Content-Type: image/jpeg');
imagejpeg($img_handle,NULL,100);
imagedestroy($img_handle);

session_start();
$_SESSION['img_number'] = $str;

更新:在测试时我注意到第一次加载图像时, session 未设置,因此当图像刷新时, session 设置为最后一个 $str值

最佳答案

如果您的 header 已发送,您可能无法调用 session_start()。

改变

header('Content-Type: image/jpeg');
imagejpeg($img_handle,NULL,100);
imagedestroy($img_handle);

session_start();
$_SESSION['img_number'] = $str;

session_start();
header('Content-Type: image/jpeg');
imagejpeg($img_handle,NULL,100);
imagedestroy($img_handle);

$_SESSION['img_number'] = $str;

关于php - session 与图像 PHP 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6163614/

相关文章:

php - 我认为我的 PHP 应用程序被 session 劫持了?

javascript - 加载页面,在 JavaScript 警报时给出变量

php - 新手程序员需要动力

java - 如何为 symfony2 创建自定义用户提供程序?

php - html/css 设计的盒子没有正确排列

php - 通过 url 传递 session ID

php - 从源页面到多个不可靠页面的 FusionCharts 集成

asp.net-mvc - ASP.NET MVC session 状态使用状态分区、MongoDB 或 Memcached 或...?

php - 我是否应该将我的 PHP5 对象存储在 SPEED session 中,为什么?

node.js - session 未在 Express 中创建