PHP:在其他目录中搜索图像是否存在并打印图像


PHP: search in other directories if image is exist and print the image

ok 我编辑了我的答案,我发现了如何在目录中找到文件,但我的问题是它不会打印图像。 这是我的代码。

<?php
$file = 'testimage.png'; 
$dir = array(
    $_SERVER['DOCUMENT_ROOT'] . "/folderA/", 
    $_SERVER['DOCUMENT_ROOT'] . "/folderB/"
);
foreach($dir as $d)
    {
    if(file_exists( $d . $file )) 
    {
        $file = $file;
    } 
}
$imgPng = imageCreateFromPng($file);
header("Content-type: image/png");
imagePng($imgPng); 
?>

为什么不打印图像?

在不添加一堆代码的情况下执行此操作的一种方法是设置include_path以查找图像文件夹,方法是在 php.ini 中修改include_path,或者在脚本中修改它:

ini_set('include_path', '/new/include/path');

然后在 fopen 中使用"use_include_path"选项。

由于您正在查看所有 php 文件夹,因此请务必检查图像文件名。

问题可能是因为$imgPng = imageCreateFromPng($file);找不到该文件。您需要指定映像的路径 $d. $file 。检查下面代码中的注释。

<?php
$file = 'testimage.png';
$dir = array($_SERVER['DOCUMENT_ROOT'] . "/folderA/", $_SERVER['DOCUMENT_ROOT'] . "/folderB/");
foreach ($dir as $d) {
    if (file_exists($d . $file)) {
        $file = $file;
        //i don't know the purpose of this but i think you want to do $file = $d . $file
    }
}
//$imgPng = imageCreateFromPng($file); //can't find the image, should be
$imgPng = imageCreateFromPng($d . $file);
header("Content-type: image/png");
imagePng($imgPng);
?>
<?php
$file = 'testimage.png'; 
$dir = [
    $_SERVER['DOCUMENT_ROOT'] . "/pathA/", 
    $_SERVER['DOCUMENT_ROOT'] . "/pathB/"];
foreach( $dir as $d )
    {
    if( file_exists( $d . $file )) 
    {
        //set image if found in the directories
        $image = $d . $file;        
    }
    else
    {
        //is not found in directories
        $image = null;
    }   
}
$img = imagecreatefrompng($image);
header("Content-type: image/png");
imagepng($img);
imagedestroy();
?>