Get name of folder within glob method - php

I'm iterating with glob through my image-folder with nested folders to find images. The structure looks like this:
-> images
-> John Doe (some names)
-> 21-09-2018 (some dates)
-> 23-09-2018 (some dates)
Now I would like to get the name of 'name'-folder and the name of the 'date'-folder in which the image is. How can I get these in my existing loop and push it to my array?
$fileArray = [];
$path = 'http://example.com/demo';
foreach (glob("images/*/*/*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE) as $curFilename)
{
$completePath = $path . '/' . $curFilename;
$FilenameWithoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($curFilename));
$basename = basename($curFilename);
if (strpos($FilenameWithoutExt, 'R') !== false) {
$eye = 'R';
}
else if (strpos($FilenameWithoutExt, 'L') !== false) {
$eye = 'L';
} else {
$eye = '';
}
$caption = $eye . ' - ' . date("d.m.Y");
$curFileObj = new mFile;
$curFileObj->caption = $caption;
$curFileObj->url = $completePath;
$curFileObj->thumbUrl = $completePath;
$curFileObj->date = date("d.m.Y");
$curFileObj->eye = $eye;
$curFileObj->basename = $basename;
array_push($fileArray, $curFileObj);
}
echo json_encode($fileArray);

SplFileInfo
You can just make a SplFileInfo object from file pathname.
For example:
$file = new SplFileInfo($curFilename);
echo $file->getPath();
will output path to your file.
There is more methods you can use, and I think you should find everything you need inside this object.
RecursiveIteratorIterator
There is also something like RecursiveIteratorIterator which will return array of SplFileInfo instead of just string pathnames like glob() does.
You can use it like:
$dir_iterator = new RecursiveDirectoryIterator('images/*/*/');
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
But inside you have to check extension if it is what you expect.
Manual
The SplFileInfo class
The RecursiveIteratorIterator class

Related

Get list of multi layered folder structure in php [duplicate]

I'd like my script to scandir recursively,
$files = scandir('/dir');
foreach($files as $file){
if(is_dir($file)){
echo '<li><label class="tree-toggler nav-header"><i class="fa fa-folder-o"></i>'.$file.'</label>';
$subfiles = scandir($rooturl.'/'.$file);
foreach($subfiles as $subfile){
// and so on and on and on
}
echo '<li>';
} else {
echo $file.'<br />';
}
}
I'd like to loop this in a way that for each dir found by scandir, it runs another scandir on the folders that have been found within that dir,
So dir 'A' contains dir 1/2/3, it should now scandir(1), scandir(2), scandir(3)
and so on for each dir found.
How can I manage to implement this easily without copy pasting the code over and over in every foreach?
EDIT: Since the answers are nearly the very same as I already tried, I'll update the question a bit.
With this script I need to create a treeview list. With the current posted scripts the following get's echo'd happens:
/images/dir1/file1.png
/images/dir1/file2.png
/images/dir1/file3.png
/images/anotherfile.php
/data/uploads/avatar.jpg
/data/config.php
index.php
What I actually need is:
<li><label>images</label>
<ul>
<li><label>dir1</label>
<ul>
<li>file1.png</li>
<li>file2.png</li>
<li>file3.png</li>
</ul>
</li>
<li>anotherfile.php</li>
</ul>
</li>
<li><label>data</label>
<ul>
<li><label>uploads</label>
<ul>
<li>avatar.jpg</li>
</ul>
</li>
<li>config.php</li>
</ul>
</li>
<li>index.php</li>
And so on, Thank you for the already posted answers!
I know this is an old question but I wrote a version of this that was more functional. It doesn't use global state and uses pure functions to figure things out:
function scanAllDir($dir) {
$result = [];
foreach(scandir($dir) as $filename) {
if ($filename[0] === '.') continue;
$filePath = $dir . '/' . $filename;
if (is_dir($filePath)) {
foreach (scanAllDir($filePath) as $childFilename) {
$result[] = $filename . '/' . $childFilename;
}
} else {
$result[] = $filename;
}
}
return $result;
}
You can scan directory recursively in this way the target is your top most directory:
function scanDir($target) {
if(is_dir($target)){
$files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned
foreach( $files as $file )
{
scanDir( $file );
}
}
}
You can adapt this function for your need easily.
For example if would use this to delete the directory and its content you could do:
function delete_files($target) {
if(is_dir($target)){
$files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned
foreach( $files as $file )
{
delete_files( $file );
}
rmdir( $target );
} elseif(is_file($target)) {
unlink( $target );
}
You can not do this in the way you are doing.
The following function gets recursively all the directories, sub directories so deep as you want and the content of them:
function assetsMap($source_dir, $directory_depth = 0, $hidden = FALSE)
{
if ($fp = #opendir($source_dir))
{
$filedata = array();
$new_depth = $directory_depth - 1;
$source_dir = rtrim($source_dir, '/').'/';
while (FALSE !== ($file = readdir($fp)))
{
// Remove '.', '..', and hidden files [optional]
if ( ! trim($file, '.') OR ($hidden == FALSE && $file[0] == '.'))
{
continue;
}
if (($directory_depth < 1 OR $new_depth > 0) && #is_dir($source_dir.$file))
{
$filedata[$file] = assetsMap($source_dir.$file.'/', $new_depth, $hidden);
}
else
{
$filedata[] = $file;
}
}
closedir($fp);
return $filedata;
}
echo 'can not open dir';
return FALSE;
}
Pass your path to the function:
$path = 'elements/images/';
$filedata = assetsMap($path, $directory_depth = 5, $hidden = FALSE);
$filedata is than an array with all founded directories and sub directories with their content. This function lets you scan the directories structure ($directory_depth) so deep as you want as well get rid of all the boring hidden files (e.g. '.','..')
All you have to do now is to use the returned array, which is the complete tree structure, to arrange the data in your view as you like.
What you are trying to do is in fact a kind of file manager and as you know there are a lot of those in the wild, open source and free.
I hope this will help you and I wish you a merry Christmas.
function getFiles(string $directory, array $allFiles = []): array
{
$files = array_diff(scandir($directory), ['.', '..']);
foreach ($files as $file) {
$fullPath = $directory. DIRECTORY_SEPARATOR .$file;
if( is_dir($fullPath) )
$allFiles += getFiles($fullPath, $allFiles);
else
$allFiles[] = $file;
}
return $allFiles;
}
I know this is old but i wanted to show a slightly different version of the other answers. Uses array_diff to discard the "." and ".." folders. Also the + operator to combine 2 arrays ( i rarely see this used so it might be useful for someone )
Though the question is old. But my answer could help people who visit this question.
This recursively scans the directory and child directories and stores the output in a global variable.
global $file_info; // All the file paths will be pushed here
$file_info = array();
/**
*
* #function recursive_scan
* #description Recursively scans a folder and its child folders
* #param $path :: Path of the folder/file
*
* */
function recursive_scan($path){
global $file_info;
$path = rtrim($path, '/');
if(!is_dir($path)) $file_info[] = $path;
else {
$files = scandir($path);
foreach($files as $file) if($file != '.' && $file != '..') recursive_scan($path . '/' . $file);
}
}
recursive_scan('/var/www/html/wp-4.7.2/wp-content/plugins/site-backup');
print_r($file_info);
Create a scan function and call it recursively...
e.g:
<?php
function scandir_rec($root)
{
echo $root . PHP_EOL;
// When it's a file or not a valid dir name
// Print it out and stop recusion
if (is_file($root) || !is_dir($root)) {
return;
}
// starts the scan
$dirs = scandir($root);
foreach ($dirs as $dir) {
if ($dir == '.' || $dir == '..') {
continue; // skip . and ..
}
$path = $root . '/' . $dir;
scandir_rec($path); // <--- CALL THE FUNCTION ITSELF TO DO THE SAME THING WITH SUB DIRS OR FILES.
}
}
// run it when needed
scandir_rec('./rootDir');
You can do a lot variation of this function. Printing a 'li' tag instead of PHP_EOL for instance, to create a tree view.
[EDIT]
<?php
function scandir_rec($root)
{
// if root is a file
if (is_file($root)) {
echo '<li>' . basename($root) . '</li>';
return;
}
if (!is_dir($root)) {
return;
}
$dirs = scandir($root);
foreach ($dirs as $dir) {
if ($dir == '.' || $dir == '..') {
continue;
}
$path = $root . '/' . $dir;
if (is_file($path)) {
// if file, create list item tag, and done.
echo '<li>' . $dir . '</li>';
} else if (is_dir($path)) {
// if dir, create list item with sub ul tag
echo '<li>';
echo '<label>' . $dir . '</label>';
echo '<ul>';
scandir_rec($path); // <--- then recursion
echo '</ul>';
echo '</li>';
}
}
}
// init call
$rootDir = 'rootDir';
echo '<ul>';
scandir_rec($rootDir);
echo '</ul>';
Modern way:
use RecursiveIteratorIterator;
use RecursiveDirectoryIterator;
$path = '/var/www/path/to/your/files/';
foreach ( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path, RecursiveDirectoryIterator::SKIP_DOTS ) ) as $file ) {
// TODO: Uncomment to see additional information. Do your manipulations with the files here.
// var_dump( $file->getPathname() ); // Or simple way: echo $file;
// var_dump( $file->isFile() );
// var_dump( $file->isDir() );
// var_dump( $file->getFileInfo() );
// var_dump( $file->getExtension() );
// var_dump( $file->getDepth() );
}
function deepScan($dir = __DIR__){
static $allFiles = [];
$allFiles[$dir] = [];
$directories = array_values(array_diff(scandir($dir), ['.', '..']));
foreach($directories as $directory){
if(is_dir("$dir\\$directory")){
foreach(deepScan("$dir\\$directory") as $key => $value) $allFiles[$key] = $value;
}
else{
$allFiles[$dir][] = "$directory";
}
}
return $allFiles;
}

How would I append tags separately in PHP?

How would I change the following code so instead of appending all tags for files together, every separate tag is stored individually, for example 'Title' would be stored within $title? Because all the tags at the moment are being stored within $aTags
The code:
// gathering all mp3 files in 'mp3' folder into array
$sDir = 'mp3/';
$aFiles = array();
$rDir = opendir($sDir);
if ($rDir) {
while ($sFile = readdir($rDir)) {
if ($sFile == '.' or $sFile == '..' or !is_file($sDir . $sFile))
continue;
$aPathInfo = pathinfo($sFile);
$sExt = strtolower($aPathInfo['extension']);
if ($sExt == 'mp3') {
$aFiles[] = $sDir . $sFile;
}
}
closedir($rDir);
}
// new object of our ID3TagsReader class
$oReader = new ID3TagsReader();
// passing through located files ..
$sList = $sList2 = '';
foreach ($aFiles as $sSingleFile) {
$aTags = $oReader->getTagsInfo($sSingleFile); // obtaining ID3 tags info
$sList .= '<tr><td>'.$aTags['Title'].'</td><td>'.$aTags['Album'].'</td>
<td>'.$aTags['Author'].'</td>
<td>'.$aTags['AlbumAuthor'].'</td>
<td>'.$aTags['Track'].'</td><td>'.$aTags['Year'].'</td>
<td>'.$aTags['Lenght'].'</td><td>'.$aTags['Lyric'].'</td>
<td>'.$aTags['Desc'].'</td>
<td>'.$aTags['Genre'].'</td></tr>';
}

php loop through files in subfolders in folder and get file paths

Im really new to PHP i searched google to find a correct script that loops through all subfolders in a folder and get all files path in that subfolder
<?php
$di = new RecursiveDirectoryIterator('posts');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
echo $filename. '<br/>';
}
?>
So i have folder 'posts' in which i have subfolder 'post001' in which i have two files
controls.png
text.txt
And the code above echos this
posts\.
posts\..
posts\post001\.
posts\post001\..
posts\post001\controls.png
posts\post001\text.txt
But i want to echo only the file paths inside these subfolders like this
posts\post001\controls.png
posts\post001\text.txt
The whole point of this is that i want to dynamically create divs for each subfolder and inside this div i put img with src and some h3 and p html tags with text equal to the .txt file so is this proper way of doing that and how to remake my php script so that i get just the file paths
So I can see the answers and they are all correct but now my point was that i need something like that
foreach( glob( 'posts/*/*' ) as $filePath ){
//create div with javascript
foreach( glob( 'posts/$filePath/*' ) as $file ){
//append img and h3 and p html tags to the div via javascript
}
//append the created div somewhere in the html again via javascript
}
So whats the correct syntax of doing these two foreach loops in php im really getting the basics now
See if this works :)
$di = new RecursiveDirectoryIterator('posts');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
if ((substr($file, -1) != '.') && (substr($file, -2) != '..')) {
echo $file . '<br/>';
}
}
<h1>Directory Listing</h1>
<?php
/**
* Recursive function to append the full path of all files in a
* given directory $dirpath to an array $context
*/
function getFilelist($dirpath, &$context){
$fileArray = scandir($dirpath);
if (count($fileArray) > 2) {
/* Remove the . (current directory) and .. (parent directory) */
array_shift($fileArray);
array_shift($fileArray);
foreach ($fileArray as $f) {
$full_path = $dirpath . DIRECTORY_SEPARATOR . $f;
/* If the file is a directory, call the function recursively */
if (is_dir($full_path)) {
getFilelist($full_path, $context);
} else {
/* else, append the full path of the file to the context array */
$context[] = $full_path;
}
}
}
}
/* $d is the root directory that you want to list */
$d = '/Users/Shared';
/* Allocate the array to store of file paths of all children */
$result = array();
getFilelist($d, $result);
$display_length = false;
if ($display_length) {
echo 'length = ' . count($result) . '<br>';
}
function FormatArrayAsUnorderedList($context) {
$ul = '<ul>';
foreach ($context as $c) {
$ul .= '<li>' . $c . '</li>';
}
$ul .= '</ul>';
return $ul;
}
$html_list = FormatArrayAsUnorderedList($result);
echo $html_list;
?>
Take a look at this:
<?php
$filename[] = 'posts\.';
$filename[] = 'posts\..';
$filename[] = 'posts\post001\.';
$filename[] = 'posts\post001\..';
$filename[] = 'posts\post001\controls.png';
$filename[] = 'posts\post001\text.txt';
foreach ($filename as $file) {
if (substr($file, -4, 1) === ".") {
echo $file."<br>";
}
}
?>
Result:
posts\post001\controls.png
posts\post001\text.txt
What this does is checking if the 4th last digit is a dot. If so, its an extension of three letters and it should be a file. You could also check for specific extensions.
$ext = substr($file, -4, 4);
if ($ext === ".gif" || $ext === ".jpg" || $ext === ".png" || $ext === ".txt") {
echo $file."<br>";
}

PHP scandir recursively

I'd like my script to scandir recursively,
$files = scandir('/dir');
foreach($files as $file){
if(is_dir($file)){
echo '<li><label class="tree-toggler nav-header"><i class="fa fa-folder-o"></i>'.$file.'</label>';
$subfiles = scandir($rooturl.'/'.$file);
foreach($subfiles as $subfile){
// and so on and on and on
}
echo '<li>';
} else {
echo $file.'<br />';
}
}
I'd like to loop this in a way that for each dir found by scandir, it runs another scandir on the folders that have been found within that dir,
So dir 'A' contains dir 1/2/3, it should now scandir(1), scandir(2), scandir(3)
and so on for each dir found.
How can I manage to implement this easily without copy pasting the code over and over in every foreach?
EDIT: Since the answers are nearly the very same as I already tried, I'll update the question a bit.
With this script I need to create a treeview list. With the current posted scripts the following get's echo'd happens:
/images/dir1/file1.png
/images/dir1/file2.png
/images/dir1/file3.png
/images/anotherfile.php
/data/uploads/avatar.jpg
/data/config.php
index.php
What I actually need is:
<li><label>images</label>
<ul>
<li><label>dir1</label>
<ul>
<li>file1.png</li>
<li>file2.png</li>
<li>file3.png</li>
</ul>
</li>
<li>anotherfile.php</li>
</ul>
</li>
<li><label>data</label>
<ul>
<li><label>uploads</label>
<ul>
<li>avatar.jpg</li>
</ul>
</li>
<li>config.php</li>
</ul>
</li>
<li>index.php</li>
And so on, Thank you for the already posted answers!
I know this is an old question but I wrote a version of this that was more functional. It doesn't use global state and uses pure functions to figure things out:
function scanAllDir($dir) {
$result = [];
foreach(scandir($dir) as $filename) {
if ($filename[0] === '.') continue;
$filePath = $dir . '/' . $filename;
if (is_dir($filePath)) {
foreach (scanAllDir($filePath) as $childFilename) {
$result[] = $filename . '/' . $childFilename;
}
} else {
$result[] = $filename;
}
}
return $result;
}
You can scan directory recursively in this way the target is your top most directory:
function scanDir($target) {
if(is_dir($target)){
$files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned
foreach( $files as $file )
{
scanDir( $file );
}
}
}
You can adapt this function for your need easily.
For example if would use this to delete the directory and its content you could do:
function delete_files($target) {
if(is_dir($target)){
$files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned
foreach( $files as $file )
{
delete_files( $file );
}
rmdir( $target );
} elseif(is_file($target)) {
unlink( $target );
}
You can not do this in the way you are doing.
The following function gets recursively all the directories, sub directories so deep as you want and the content of them:
function assetsMap($source_dir, $directory_depth = 0, $hidden = FALSE)
{
if ($fp = #opendir($source_dir))
{
$filedata = array();
$new_depth = $directory_depth - 1;
$source_dir = rtrim($source_dir, '/').'/';
while (FALSE !== ($file = readdir($fp)))
{
// Remove '.', '..', and hidden files [optional]
if ( ! trim($file, '.') OR ($hidden == FALSE && $file[0] == '.'))
{
continue;
}
if (($directory_depth < 1 OR $new_depth > 0) && #is_dir($source_dir.$file))
{
$filedata[$file] = assetsMap($source_dir.$file.'/', $new_depth, $hidden);
}
else
{
$filedata[] = $file;
}
}
closedir($fp);
return $filedata;
}
echo 'can not open dir';
return FALSE;
}
Pass your path to the function:
$path = 'elements/images/';
$filedata = assetsMap($path, $directory_depth = 5, $hidden = FALSE);
$filedata is than an array with all founded directories and sub directories with their content. This function lets you scan the directories structure ($directory_depth) so deep as you want as well get rid of all the boring hidden files (e.g. '.','..')
All you have to do now is to use the returned array, which is the complete tree structure, to arrange the data in your view as you like.
What you are trying to do is in fact a kind of file manager and as you know there are a lot of those in the wild, open source and free.
I hope this will help you and I wish you a merry Christmas.
function getFiles(string $directory, array $allFiles = []): array
{
$files = array_diff(scandir($directory), ['.', '..']);
foreach ($files as $file) {
$fullPath = $directory. DIRECTORY_SEPARATOR .$file;
if( is_dir($fullPath) )
$allFiles += getFiles($fullPath, $allFiles);
else
$allFiles[] = $file;
}
return $allFiles;
}
I know this is old but i wanted to show a slightly different version of the other answers. Uses array_diff to discard the "." and ".." folders. Also the + operator to combine 2 arrays ( i rarely see this used so it might be useful for someone )
Though the question is old. But my answer could help people who visit this question.
This recursively scans the directory and child directories and stores the output in a global variable.
global $file_info; // All the file paths will be pushed here
$file_info = array();
/**
*
* #function recursive_scan
* #description Recursively scans a folder and its child folders
* #param $path :: Path of the folder/file
*
* */
function recursive_scan($path){
global $file_info;
$path = rtrim($path, '/');
if(!is_dir($path)) $file_info[] = $path;
else {
$files = scandir($path);
foreach($files as $file) if($file != '.' && $file != '..') recursive_scan($path . '/' . $file);
}
}
recursive_scan('/var/www/html/wp-4.7.2/wp-content/plugins/site-backup');
print_r($file_info);
Create a scan function and call it recursively...
e.g:
<?php
function scandir_rec($root)
{
echo $root . PHP_EOL;
// When it's a file or not a valid dir name
// Print it out and stop recusion
if (is_file($root) || !is_dir($root)) {
return;
}
// starts the scan
$dirs = scandir($root);
foreach ($dirs as $dir) {
if ($dir == '.' || $dir == '..') {
continue; // skip . and ..
}
$path = $root . '/' . $dir;
scandir_rec($path); // <--- CALL THE FUNCTION ITSELF TO DO THE SAME THING WITH SUB DIRS OR FILES.
}
}
// run it when needed
scandir_rec('./rootDir');
You can do a lot variation of this function. Printing a 'li' tag instead of PHP_EOL for instance, to create a tree view.
[EDIT]
<?php
function scandir_rec($root)
{
// if root is a file
if (is_file($root)) {
echo '<li>' . basename($root) . '</li>';
return;
}
if (!is_dir($root)) {
return;
}
$dirs = scandir($root);
foreach ($dirs as $dir) {
if ($dir == '.' || $dir == '..') {
continue;
}
$path = $root . '/' . $dir;
if (is_file($path)) {
// if file, create list item tag, and done.
echo '<li>' . $dir . '</li>';
} else if (is_dir($path)) {
// if dir, create list item with sub ul tag
echo '<li>';
echo '<label>' . $dir . '</label>';
echo '<ul>';
scandir_rec($path); // <--- then recursion
echo '</ul>';
echo '</li>';
}
}
}
// init call
$rootDir = 'rootDir';
echo '<ul>';
scandir_rec($rootDir);
echo '</ul>';
Modern way:
use RecursiveIteratorIterator;
use RecursiveDirectoryIterator;
$path = '/var/www/path/to/your/files/';
foreach ( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path, RecursiveDirectoryIterator::SKIP_DOTS ) ) as $file ) {
// TODO: Uncomment to see additional information. Do your manipulations with the files here.
// var_dump( $file->getPathname() ); // Or simple way: echo $file;
// var_dump( $file->isFile() );
// var_dump( $file->isDir() );
// var_dump( $file->getFileInfo() );
// var_dump( $file->getExtension() );
// var_dump( $file->getDepth() );
}
function deepScan($dir = __DIR__){
static $allFiles = [];
$allFiles[$dir] = [];
$directories = array_values(array_diff(scandir($dir), ['.', '..']));
foreach($directories as $directory){
if(is_dir("$dir\\$directory")){
foreach(deepScan("$dir\\$directory") as $key => $value) $allFiles[$key] = $value;
}
else{
$allFiles[$dir][] = "$directory";
}
}
return $allFiles;
}

Multiple File Exists Checking? A Better way?

I have a script. It recieves a variable called $node, which is a string; for now, lets assume the variable value is "NODEVALUE". When the script is called, it takes the variable $node, and tries to find an image called NODEVALUE.png. If it cant find that image, it then checks for NODEVALUE.jpg, if it can't find that it looks for NODEVALUE.gif... and after all that, it still cant find, it returns RANDOM.png.
Right now I am doing this script as follows:
if (file_exists($img = $node.".png")) { }
else if (file_exists($img = $node.".jpg")) { }
else if (file_exists($img = $node.".gif")) { }
else
{
$img = 'RANDOM.png';
}
There has to be a better way than this... anyone have any ideas?
$list = array_filter(array("$node.png", "$node.jpg", "$node.gif"), 'file_exists');
if (!$img = array_shift($list)) {
$img = 'RANDOM.png';
}
Alternatives :
$list = scandir(".");
$list = preg_grep("#".preg_quote($node,'#')."\.(jpg|png|gif)$#", $list);
This returns a list of file names that start with $node and with a .jpg, .png or .gif suffix.
If the directory contains many entries, if may be faster to use glob() first:
$list = glob("$node.*"); // take care to escape $node here
$list = preg_grep("#".preg_quote($node,'#')."\.(jpg|png|gif)$#");
The preg_grep() can also be replaced by
$list = array_intersect($list, array("$node.png", "$node.jpg", "$node.gif"));
Or with a loop:
$img = null;
foreach(array('png','jpg','gif') as $ext) {
if (!file_exists("$node.$ext")) continue;
$img = "$node.$ext"; break;
}
$img = $img ? $img : "RANDOM.png";
The most compact (and therefore not recommended) form would be:
if (array_sum(array_map("file_exists", array($fn1, $fn2, $fn3)))) {
It could be adapted to also returning the found filename using array_search:
array_search(1, array_map("file_exists", array($fn1=>$fn1, $fn2=>$fn2)))
Hardly readable. Note how it also requires a map like array("$node.png"=>"$node.png", "$node.gif"=>"$node.gif", ...). So it would not be that much shorter.
$n_folder="images/nodes/";
$u_folder="images/users/";
$extensions=array(".png",".jpg",".gif");
foreach ($extensions as $ext)
{
if (file_exists($n_folder.$node.$ext))
{
$img=$n_folder.$node.$ext;
break;
}
elseif (file_exists($u_folder.$node.$ext))
{
$img=$u_folder.$node.$ext;
break;
}
}
if (!$img)
{
random image generator script...
}
Okay... this is what I finalized on:
$searches = array(
$folder . "nodes/" . $node . ".png",
$folder . "nodes/" . $node . ".jpg",
$folder . "nodes/" . $node . ".gif",
$folder . "users/" . $user . ".png",
$folder . "users/" . $user . ".jpg",
$folder . "users/" . $user . ".gif"
);
foreach ($searches AS $search)
{
if (file_exists($search))
{
$img = $search;
break;
}
}
if (!$img)
{
random image generator script...
}

Categories