图像无法显示,因为它包含错误php

时间:2012-10-21 22:53:53

标签: php gd

  

可能重复:
  Does html can be use with dynamic generated images in php?

我正在尝试在php中生成验证码。我相信我的代码是正确的,但我无法在浏览器上获取图像..这是代码:

<!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>Untitled Document</title>
</head>
<body>
<?php header('Content-type: image/png');?>
<?php session_start();
$md5 = md5(microtime() * time() );
$string = substr($md5, -5);
$captcha = imagecreatefrompng("./captcha.png");
$black = imagecolorallocate($captcha, 0, 0, 0);
$line = imagecolorallocate($captcha,233,239,239);
imageline($captcha,0,0,39,29,$line);
imageline($captcha,40,0,64,29,$line);
$_SESSION['key'] = md5($string);
imagestring($captcha, 5, 20, 10, $string, $black);
imagepng($captcha);?> 
</body>
</html>

png图像与此代码位于同一文件夹中。在php中启用了GD选项..我一无所知..感谢您的帮助

2 个答案:

答案 0 :(得分:0)

在设置<?php header('Content-type: image/png');?>session_start();

之前,您无法输出任何内容

您需要创建一个处理图像的图像脚本,然后链接到html中的该脚本

例如: captcha.php

<?php 
session_start();
header('Content-type: image/png');
$md5 = md5(microtime() * time() );
$string = substr($md5, -5);
$captcha = imagecreatefrompng("./captcha.png");
$black = imagecolorallocate($captcha, 0, 0, 0);
$line = imagecolorallocate($captcha,233,239,239);
imageline($captcha,0,0,39,29,$line);
imageline($captcha,40,0,64,29,$line);
$_SESSION['key'] = md5($string);
imagestring($captcha, 5, 20, 10, $string, $black);
imagepng($captcha);
?>

您的HTML

<?php 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>Untitled Document</title>
</head>
<body>
<img src="captcha.php"/>
</body>
</html>

答案 1 :(得分:0)

我猜这是你的CAPTCHA图像的来源(例如“image.php”文件),它是从其他地方加载的(例如来自“captcha.php”和<img src="image.php" />)。您可能还必须在“captcha.php”文件中包含session_start()

根据您发布的代码,只需删除所有HTML。

此外,作为一项规则,永远不会发送图像内容类型,直到您准备好(并首先检查错误,如果合适)。

<?php
    session_start();
    $md5 = md5(microtime() * time() );
    $string = substr($md5, -5);
    $captcha = imagecreatefrompng("./captcha.png");
    $black = imagecolorallocate($captcha, 0, 0, 0);
    $line = imagecolorallocate($captcha,233,239,239);
    imageline($captcha,0,0,39,29,$line);
    imageline($captcha,40,0,64,29,$line);
    $_SESSION['key'] = md5($string);
    imagestring($captcha, 5, 20, 10, $string, $black);
    Header('Content-type: image/png');
    imagepng($captcha);
?>

注意:您正在运行MD5字符串的MD5。那是对的吗?为什么不使用uniqid()代替md5(microtime() * time() ),并将$md5存储在_SESSION