-4

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;
  • 1
    "I currently can't find the code but will upload it later." ok then, i'll wait ... –  Oct 31 '17 at 23:07
  • 1
    Possible duplicate of [PHP: rename all files to lower case in a directory recursively](https://stackoverflow.com/questions/32173320/php-rename-all-files-to-lower-case-in-a-directory-recursively) – Nic3500 Nov 01 '17 at 00:07
  • Sorry for not uploading the code right away. It was already 2am and my gf was yelling at me. Spent all day trying to find a way to do this. – feratechinc Nov 01 '17 at 09:23

1 Answers1

1

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

}