recursion - PHP: recursively remove brackets from filenames in directory and all sub directories
Get the solution ↓↓↓I'm having an issue getting rid of brackets in uploaded files in a system.
I'm able to remove the brackets in the files of a single directory but I'm struggling to get this working recursively in the sub directories of the same folder.
I'm using str_replace to find the brackets [ ] and replacing them with a blank character.
$dir = $_SERVER["DOCUMENT_ROOT"]."/uploads" ; // what directory to parse
if ( $handle = opendir ( $dir)) {
print "Directory Handle = $handles\n" ;
print "Files : \n" ;
while ( false !== ($file = readdir($handle))) {
if ( $file != "." && $file != ".." ) {
$isdir = is_dir ( $file ) ;
if ( $isdir == "1" ) {} // if its a directory do nothing
else {
$file_array[] = "$file" ; // get all the file names and put them in an array
print "$file\n" ;
} // closes else
} // closes directory check
} // closes while
} // closes opendir
//Lets go through the array
$arr_count = count( $file_array ) ; // find out how many files we have found so we can initiliase the counter
for ( $counter=1; $counter<$arr_count; $counter++ ) {
print "Array = $file_array[$counter]\n" ; // tell me how many files there are
$illegals = array("[","]");
$new = str_replace ( $illegals, "", $file_array[$counter] ) ; // now create the new file name
$ren = rename ( "$dir/$file_array[$counter]" , "$dir/$new" ) ; // now do the actual file rename
print "$new\n" ; // print out the new file name
}
closedir ( $handle ) ;
echo $dir;
Answer
Solution:
Ok so I took the code from the recursive renaming script and created my own sanitize script. Please let me know if I screwed anything up. Thanks for pointing me in the right direction NIC3500
$path = $_SERVER["DOCUMENT_ROOT"]."/uploads" ;
$illegals = array("[","]");
$di = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach($di as $name => $fio) {
//$newname = $fio->getPath() . DIRECTORY_SEPARATOR . strtolower( $fio->getFilename() );
$newname = $fio->getPath() . DIRECTORY_SEPARATOR . str_replace ( $illegals, "", $fio->getFilename() );
//echo $newname, "\r\n";
rename($name, $newname);
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the requested url was not found on this server. xampp
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.