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

Php 无法显示图像,因为它包含错误,php,gd,Php,Gd,可能重复: 我正在尝试用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> <m

可能重复:

我正在尝试用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图像与此代码位于同一文件夹中。GD选项在php中已启用..我不知道..非常感谢您的帮助..谢谢您

在设置
会话_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>

无标题文件

我猜这是您的验证码图像的来源(例如“image.php”文件),它是从其他地方加载的(例如,从带有
的“CAPTCHA.php”)。您可能还必须在“captcha.php”文件中包含
session\u start()

从您发布的代码中,只需删除所有HTML即可

另外,作为一项规则,在准备好之前,永远不要发送图像内容类型(如果合适,首先检查错误)



注意:您正在运行MD5字符串的MD5。对吗?为什么不使用
uniqid()
而不是
md5(microtime()*time())
,并在
\u会话中存储
$md5

所有这些“在此处输入代码”是怎么回事?
<?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);
?>