-1

可能重复:
html 是否可以与 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 选项..我一无所知..任何帮助表示赞赏...谢谢

4

2 回答 2

0

<?php header('Content-type: image/png');?>在设置或之前你不能输出任何东西session_start();

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

示例:验证码.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>
于 2012-10-21T23:07:14.730 回答
0

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

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

此外,作为一项规则,在您准备好之前永远不要发送 Image 内容类型(如果合适,请先检查错误)。

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

于 2012-10-21T23:08:38.003 回答