KingDoppel
KingDoppel

Reputation: 79

PHP: what is the convinient or enhanced code for searching a current file in directories?

I have my code below. It searches the image in 2 directories and it will print the image if the image is found or it will not show the image if not found.

<?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);
?>

Can someone provide me a enchance or convinient way of a code above?

Upvotes: 0

Views: 74

Answers (2)

SpazzMarticus
SpazzMarticus

Reputation: 1278

You can set the $image = null; as a default, so you don't have to check empty($image) and you can add a break to the loop, so you don't always have to look in both pathes, if you have already found it in the first path:

 $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

You can't really simplify the check, because at some level you have to use a function like "file_exists" that returns if the file exists. And if you have different pathes, you also have to check until you find it (or it doesn't exist)

So: Your code is fine.

Upvotes: 1

Jan Jakeš
Jan Jakeš

Reputation: 2669

A much more convenient way of doing such things is using third-party libraries. If you are OK with that you can look into Nette Finder or Symfony Finder (or any other similar library).

With Nette Finder the example then could look like this:

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

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

If you have just this one script working with files, it would probably be an overkill. However, if you are working with files a little bit more it's definitely worth a try.

Upvotes: 0

Related Questions