PHP / HTML - 从外部根文件夹加载图像

时间:2016-05-09 08:07:51

标签: php html image

我正在尝试在HTML中的<img>标记中加载图片。 我的图像文件夹与根文件夹位于同一文件夹中,这意味着我需要上一个文件夹才能访问图像文件夹。

我环顾互联网并发现该方法在图片的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>标记内根文件夹外的文件夹中的图片。

1 个答案:

答案 0 :(得分:3)

使用PHP作为base64图像获取该图像,并输出该内容以及正确的标题:

[imageRequest.php?requested=some_file.png]

$imagesDir = __DIR__.'/../';
$content = file_get_contents($imagesDir.$_GET['requested']);
$content = base64_encode($content);

$data = "data:image/png;base64,{$content}";

header('Content-Type: image/png');
echo base64_decode($data);`
相关问题