【发布时间】:2016-08-03 22:32:14
【问题描述】:
我不确定这是否可能,但可以。
我有一个目录,里面有我需要使用 PHP 读取的图像文件。然后我需要将它们转换为 html img 元素以在画廊中使用。
我已链接此页面 (http://www.mysql-apache-php.com/fileupload-security.htm) 以用作此作业的参考。它显示了一个使用 imagecreatefromjpeg()、imagecreatefrompng() 和 imagecreatefromgif() 的示例:
示例代码
// this is just example only
$imgfile = $rsPhoto['photo']; // or value from database
list($width, $height, $type, $attr) = getimagesize($imgfile);
switch ($type)
{
case 1: $im = imagecreatefromgif($imgfile);
header("Content-type: image/gif");
break;
case 2:
$im = imagecreatefromjpeg($imgfile);
header("Content-type: image/jpeg");
break;
case 3:
$im = imagecreatefrompng($imgfile);
header("Content-type: image/png");
break;
}
我根本不明白它在做什么。不知何故,它得到了某种奇怪的 php 对象文件,然后……将其显示为整个页面?它在哪里/如何/为什么这样做?
以下是我希望页面执行的操作。 createGalleryEl 不起作用,给我错误,告诉我文件不存在。这是因为我的 .htaccess 文件吗?
gallery.php
<?php
//Create the basic headers, etc.
echo "<head>"
."<title>Photo Gallery</title>"
.'<link rel="stylesheet" type="text/css" href="style.css">'
.'<meta charset="UTF-8">'
."</head>";
echo "<body>";
echo "<h1>Photo Gallery</h1>";
echo "<div id='gallery'>";
/*Get all files in uploads. Check if they're image files. If they are,
create gallery elements for them with thumbnails and all. */
$files1 = scandir("uploads/");
foreach($files1 as $thisFile) {
$whitelist = array(".png", ".gif", "jpg", ".jpeg");
foreach ($whitelist as $file) {
if(preg_match("/$file\$/i", $thisFile)) {
//Create the gallery element for it.
createGalleryEl($thisFile);
}
}
}
echo '</div>'; //end of gallery
echo '</body>';
//Creates the actual element for the gallery.
function createGalleryEl($filename) {
echo "<div class='thumbnail'><img src='uploads/$filename'></div>";
}
?>
.htaccess
Options -Indexes
Options -ExecCGI
AddHandler cgi-script .php .php3 .php4 .phtml .pl .py .jsp .asp .htm .shtml .sh .cgi
php_flag allow_url_fopen On
<Files ^(*.jpeg|*.jpg|*.png|*.gif)>
order deny,allow
deny from all
</Files>
鉴于此设置,我如何获取图像文件并将它们放入 html img 元素?
另外,如果我完全误解了这种事情的工作原理,请告诉我。我根本不习惯 PHP 和服务器端开发作为一个整体,所以我可能对这些东西的大部分知识有所疏忽。
【问题讨论】:
-
我不明白你为什么需要 imagecreatefromgif(etc)
-
难道不是因为我无法直接链接到文件本身(因为出于安全原因,我已将其限制在 .htaccess 文件中)?有没有办法在使用这些功能的同时做到这一点?
-
好的,更关键的问题:使用上面的 .htaccess 文件,我能以某种方式让图像显示在 html img 元素中吗?以任何可能的方式?
-
你认为你保护他们免受什么伤害?
-
防止人们在我的服务器上运行脚本?