Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:在目录中搜索当前文件的方便或增强的代码是什么?_Php_Image_Search_Path_Directory - Fatal编程技术网

PHP:在目录中搜索当前文件的方便或增强的代码是什么?

PHP:在目录中搜索当前文件的方便或增强的代码是什么?,php,image,search,path,directory,Php,Image,Search,Path,Directory,我的代码在下面。它在2个目录中搜索图像,如果找到图像,它将打印图像;如果没有找到,它将不显示图像 <?php $file = 'testimage.png'; $dir = [$_SERVER['DOCUMENT_ROOT'] . "/pathA/", $_SERVER['DOCUMENT_ROOT'] . "/pathB/"]; foreach( $dir as $d ) { if( file_exists( $d . $file )) {

我的代码在下面。它在2个目录中搜索图像,如果找到图像,它将打印图像;如果没有找到,它将不显示图像

<?php
$file = 'testimage.png'; 

$dir = 
   [$_SERVER['DOCUMENT_ROOT'] . "/pathA/", 
    $_SERVER['DOCUMENT_ROOT'] . "/pathB/"];

foreach( $dir as $d )
{

    if( file_exists( $d . $file )) 
    {
        $image = $d . $file;    
    }

}

if(empty($image))
{
    $image = null;
}

$img = imagecreatefrompng($image);

header("Content-type: image/png");
imagePng($img);
?>


有人能为我提供一种增强或方便的方法来处理上面的代码吗?

更方便的方法是使用第三方库。如果您对此没有意见,您可以查看或(或任何其他类似的库)

使用Nette Finder,示例可能如下所示:

$images = iterator_to_array(Finder::findFiles($file)->in($dir));
$image = $images ? reset($images) : NULL;

$img = imagecreatefrompng($image->getPath());
// ...

如果您只使用这一个脚本处理文件,那么这可能是一种过度使用。但是,如果您正在处理更多的文件,则绝对值得一试。

您可以将$image=null;默认情况下,您不必选中空($image),也可以在循环中添加一个中断,因此,如果您已在第一个路径中找到它,则不必始终在两个路径中查找:

 $image = null;
 foreach( $dir as $d )
 {

    if( file_exists( $d . $file )) 
    {
        $image = $d . $file;    
        break; //Exit loop when the file is found
    }

 } 
 //Remove empty($image)-Check
您无法真正简化检查,因为在某种程度上,您必须使用“file_exists”之类的函数,如果文件存在,则返回该函数。如果你有不同的路径,你也必须检查直到你找到它(或者它不存在)


所以:您的代码很好。

您到底不喜欢这段代码的哪些方面?我不认为有什么比你的任务更方便的了?减少“如果声明”我不想使用第三方。在上面的代码中有没有其他不使用第三方的方法?没有,你的代码很好。我想你会觉得PHP文件函数不舒服,这就是为什么我给你指出了第三方libs。我不能把else语句放在if语句之后为什么?谢谢你,代码和你的一样,但你把它写成$image=null;它保持变量$image=null;甚至该文件也存在。是否最好同时使用?如果?哪一种执行速度更快?Foreach是迄今为止最快的。检查:PHP性能问题。它有助于编写性能良好的代码。