Created
June 2, 2019 09:28
-
-
Save ppabcd/6c5a276dd4b9d4ecdb252ff28241c9ad to your computer and use it in GitHub Desktop.
Sort File by Extension Inside Folder Using PHP
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
<?php | |
$folder = __DIR__."/experimen/"; | |
$moved_folder = __DIR__."/hasil/"; | |
$extensions = [ | |
"gambar" => ["jpg","png", "jpeg", "JPG", "svg"], | |
"video" => ["mkv", "mp4"], | |
"musik" => ["mp3"], | |
"document" => ["pdf","txt","xls", "epub", "docx", "xlsb"], | |
"compressed" => ["rar","zip", "tar.gz"], | |
"programming" => ["php", "py", "sql", "js", "html", "htm", "map", "phar"], | |
"windows_installer" => ["exe"], | |
"installer" => ["deb", "bin", "run"], | |
"shell" => ["sh"], | |
"vpn" => ["ovpn"], | |
"flash" => ["swf"], | |
"java" => ["jar", "java", "javac"], | |
"other" => [""] | |
]; | |
function cek_folder($dir){ | |
if(!file_exists($dir)){ | |
mkdir($dir); | |
} | |
} | |
function generate_insensitive($ext){ | |
$text = ""; | |
$length_string = strlen($ext); | |
for($i=0; $i<$length_string; $i++){ | |
$text .= "["; | |
$text .= strtolower($ext[$i]); | |
$text .= strtoupper($ext[$i]); | |
$text .= "]"; | |
} | |
return $text; | |
} | |
function glob_recursive($pattern, $flags = 0){ | |
$files = glob($pattern, $flags); | |
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) | |
{ | |
$files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags)); | |
} | |
return $files; | |
} | |
foreach($extensions as $key => $extension){ | |
$moved_folder_new = $moved_folder.$key.'/'; | |
cek_folder($moved_folder_new); | |
array_map(function($ext) use ($folder, $moved_folder_new, $key){ | |
$ext = generate_insensitive($ext); | |
$files = glob_recursive($folder."*.".$ext); | |
if($key == "other"){ | |
$files = glob_recursive($folder."*"); | |
} | |
foreach($files as $file){ | |
if(!is_file($file)){ | |
continue; | |
} | |
echo "Moving ".$file." to ".$moved_folder_new.basename($file)."\n"; | |
rename($file, $moved_folder_new.basename($file)); | |
} | |
},$extension); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment