[英]PHP file as image source doesn't work (HTML, PHP)
我的php文件创建了一个png图像。 图像已准备就绪,已保存到给定的文件夹中,但无法将其加载到页面上(它仅显示图像的位置,但为空白)。
这是“ captcha_image.php”:
<?php
$dirPath="/opt/lampp/htdocs/WebSiteFolder/dfxCaptcha/";
$font='/opt/lampp/htdocs/WebSiteFolder/DejaVuSerif-Bold.ttf';
$imgWidth=200;
$imgHeight=50;
global $image;
$image = imagecreatetruecolor($imgWidth, $imgHeight) or die("Cannot initialize a new GD image stream.");
$background_color = imagecolorallocate($image, 0, 0, 0);
$text_color = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image, 0, 0, $imgWidth, $imgHeight, $background_color);
$letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$len = strlen($letters);
$letter = $letters[rand(0, $len - 1)];
$word = "";
for ($i = 0; $i < 4; $i++) {
$letter = $letters[rand(0, $len - 1)];
imagettftext($image, 15, 0, $i*50+25, 50, $text_color, $font, $letter);
$word .= $letter;
}
$_SESSION['captcha_string'] = $word;
$images = glob($dirPath."*.png");
foreach ($images as $image_to_delete) {
@unlink($image_to_delete);
}
header ("Content-type: image/png");
imagepng($image, $dirPath."image" . time() . ".png");
?>
我在HTML中使用它:
<img src="includes/captcha_image.php" id="captcha">
如何在页面上显示图像?
captcha_image.php
文件不会将文件输出到浏览器,因为您为imagepng
函数提供了两个参数。
该文件说:
至
将文件保存到的路径或开放流资源(此函数返回后将自动关闭)。 如果未设置或为NULL,则原始图像流将直接输出。
您可能不想指定第二个参数–但是,这将意味着未保存图像。 您没有向我们展示您接受CAPTCHA的逻辑,但它似乎涉及会话管理,在这种情况下,您无需保存文件。
这应该是您的最后一行:
imagepng($image);
此外,请考虑使用现有的CAPTCHA解决方案。 您在代码中所做的工作会产生清晰的文本,如今,OCR机器人对这些文本非常可读。 根据项目的目的,您甚至可能没有验证码(例如,对于博客文章的评论,您可以指定隐藏的表单字段,然后使用垃圾邮件过滤器)。 如果CAPTCHA确实至关重要,那么您将需要比现有解决方案更好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.