Last active
July 20, 2017 07:47
-
-
Save Artem-Schander/a46fd2b9ad2fa82a23092ec23131f937 to your computer and use it in GitHub Desktop.
Find files in specific folder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function scanDir($dir, $contains = null, $sort = 'date', $order = 'ASC', $ignored = array('.', '..', '.htaccess')) | |
{ | |
$files = array(); | |
$finfo = finfo_open(FILEINFO_MIME_TYPE); | |
// die('/'.$contains.'(\D)/'); | |
foreach (scandir($dir) as $i => $file) { | |
if (in_array($file, $ignored)) { | |
continue; | |
} | |
if (isset($contains) && is_string($contains)) { | |
$key = $contains; | |
preg_match('/' . $key . '(\D)/i', $file, $matches); | |
if (count($matches) === 0) { | |
continue; | |
} | |
} else if (isset($contains) && is_array($contains)) { | |
$continue = false; | |
foreach ($contains as $key) { | |
preg_match('/' . $key . '(\D)/i', $file, $matches); | |
if (count($matches) === 0) { | |
$continue = true; | |
continue; | |
} | |
} | |
if ($continue) { | |
continue; | |
} | |
} | |
$files[$i] = array( | |
'iter' => $i, | |
'date' => filemtime($dir . '/' . $file), | |
'name' => pathinfo($file, PATHINFO_FILENAME), | |
'file' => $file, | |
'path' => $dir, | |
'size' => humanFilesize(filesize($dir . '/' . $file)), | |
'mime' => finfo_file($finfo, $dir . '/' . $file), | |
'type' => MIME::group(pathinfo($dir . '/' . $file, PATHINFO_EXTENSION)), | |
'sort-name' => strtolower(trim(str_replace($contains, '', pathinfo($file, PATHINFO_FILENAME)))), | |
'sort-size' => filesize($dir . '/' . $file), | |
); | |
} | |
finfo_close($finfo); | |
usort($files, function ($a, $b) use ($sort, $order) { | |
if (is_string($a[$sort])) { | |
if ($order === 'ASC') { | |
return strcmp(static::slug($a[$sort]), static::slug($b[$sort])); | |
} | |
if ($order === 'DESC') { | |
return strcmp(static::slug($b[$sort]), static::slug($a[$sort])); | |
} | |
} else { | |
if ($order === 'ASC') { | |
return $a[$sort] - $b[$sort]; | |
} | |
if ($order === 'DESC') { | |
return $b[$sort] - $a[$sort]; | |
} | |
} | |
}); | |
return ($files) ? $files : []; | |
} | |
function humanFilesize($bytes, $decimals = 2) | |
{ | |
$sz = array('B', 'KB', 'MB', 'GB', 'TB', 'PB'); | |
$factor = floor((strlen($bytes) - 1) / 3); | |
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) .' '. @$sz[$factor]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment