【发布时间】:2016-09-03 18:47:53
【问题描述】:
我正在尝试在 HTML 中的 <img> 标记中加载图像。
我的 images 文件夹与根文件夹在同一个文件夹中,这意味着我需要上一个文件夹才能访问 images 文件夹。
我浏览了互联网,找到了在图像的 src 属性中使用 GET 请求的方法,不幸的是没有成功。
文件夹结构:
img >
somefile.png
foo.png
bar.png
html >
index.php
imageRequest.php
//other root files
我不能使用以下内容:<img src="../img/somefile.png">,因为它指向不存在的东西(呃!)。所以我尝试使用 GET 请求。
我的 HTML
<div>
<img src="imageRequest.php?requested=somefile.png">
</div>
我的 PHP (imageRequest.php)
$fileName = $_GET['requested'];
fetchImage();
function fetchImage(){
global $fileName;
if(!isset($fileName)) return;
$filePath = dirname($_SERVER['DOCUMENT_ROOT'])."/img/".$fileName;
if(file_exists($filePath)){
readfile($filePath);
}
}
TL;DR:使用<img> 标记内根文件夹之外的文件夹中的图像。
【问题讨论】:
-
因为你的文件夹在你的根目录之外,你不能使用
DOCUMENT_ROOT...如果你有权限你可以在你的函数fetchImage()中使用绝对路径。我还建议您将变量$fileName传递给您的函数并且不要在那里使用全局变量。 -
@RaphaelMüller 目录名($dir);抓取父文件夹,这是我需要的文件夹;)。不过感谢您的提示。