Php绝对路径不适用于glob函数

问题描述

我正在尝试渲染特定文件夹中的所有图像,但显示的是空白图像。如何提供正确的文件绝对路径以仅呈现特定类型的图像。浏览器中从本地文件夹渲染的图片数量完全相同,但所有图片都是空白的。

Output

<?PHP
ini_get("include_path"));
$root = $_SERVER['DOCUMENT_ROOT'];
$dirname = ($root . "/folder/assets/img/post/cards/");
/img/post/cards/');
$images = glob($dirname . "*.png");
foreach ($images as $image) {
    echo '<div class="col-lg-4 padd-10">
            <div class="posters text-center">
                <a href="image-editor.PHP?image_path=' . $image . '">
                    <img src="' . $image . '" >
                </a>
            </div>
            <div class="poster-actions">
                <a href="./assets/img/post/Bright-Happy-Birthday.png" download target="_blank">Download</a>
                <a href="image-editor.PHP?image_path= ' . $image . '">Edit</a>
            </div>
        </div>';
}
?>

解决方法

我想我的处理方式可能略有不同。要修改你的,我会做几件事:

  1. 在域根目录中创建各种配置文件,您可以在其中定义目录路径等重要元素

/var/www/html/folder/config.php

<?php
define('DS',DIRECTORY_SEPARATOR);
# Set the root here which,in this instance,would write:
# /var/www/html/folder
define('DOMAIN_ROOT',__DIR__);
# Set your assets folder when called in browser
define('MEDIA_ASSETS','/assets');
# Set your image folder when called in browser
define('MEDIA_IMAGES',MEDIA_ASSETS.'/img');
  1. 现在在您使用图库构建的文件中,您需要包含此配置:

/var/www/html/folder/whatever-this-is- called.php

<?php
# Include the config
include_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
ini_get("include_path"));

# Real path to the file
$filePath = DOMAIN_ROOT.str_replace('/',DS,MEDIA_IMAGES).DS.'post'.DS.'cards';
# Browser view file path
$domainPath = MEDIA_IMAGES.'/post/cards';
# Fetch files
$images = glob($filePath . "*.png");
# Loop over the found files
foreach($images as $image):
    # Store the file name
    $fname = basename($image); ?>

<div class="col-lg-4 padd-10">
    <div class="posters text-center">
        <a href="image-editor.php?image_path=<?php echo $path = base64_encode($images) ?>">
            <img src="<?php echo $dpath = "{$domainPath}/{$fname}" ?>" />
        </a>
    </div>
    <div class="poster-actions">
        <a href="<?php echo $dpath ?>" download target="_blank">Download</a>
        <a href="image-editor.php?image_path=<?php echo $path ?>">Edit</a>
    </div>
</div>

<?php endforeach;

另一种方法是将这些文件名保存到数据库中,以便于获取和验证等等。使用您所拥有的,您必须小心验证发送到 image-editor.php 的路径,以确保有人无法编辑您系统上意外的文件/图像。

注意,我还没有测试过这个,但是有足够的注释来了解要完成的工作。