Hi, Right now i am using the code below to delete all the files in a given directiory and delete the folder. PHP: /** * Recursively delete a directory * * @param string $dir * Directory name * @param boolean $deleteRootToo * Delete specified top-level directory as well */ public function unlinkRecursive($dir, $deleteRootToo) { if (! $dh = @opendir ( $dir )) { return; } while ( false !== ($obj = readdir ( $dh )) ) { if ($obj == '.' || $obj == '..') { continue; } if (! @unlink ( $dir . '/' . $obj )) { $this->unlinkRecursive ( $dir . '/' . $obj, true ); } } closedir ( $dh ); if ($deleteRootToo) { @rmdir ( $dir ); } return;} However i would like to know how, instead of deleting every file, how can i delete all the files that have the extension mcr forexample? that would mean that if the folder contained files with diffrent extensions. such as mcr, mca, mcapm etc, it would only delete all the mcr files. Weird question but please help me
Use substr. PHP: function fileHasExtension(string $file, string $extension) : bool{ return substr($file, -strlen($extension)) === $extension;}
Very grateful for your help however iv tried playing round with that bit of code in my one but i cant seem to get it to work. im not really sure what the right way is to add it :/ this is what i tried PHP: /** * Recursively delete a directory * * @param string $dir * Directory name * @param boolean $deleteRootToo * Delete specified top-level directory as well */ public function unlinkRecursive($dir, $deleteRootToo) { if (! $dh = @opendir ( $dir )) { return; } while ( false !== ($obj = readdir ( $dh )) ) { if ($obj == '.' || $obj == '..') { continue; } if (! @unlink ( $dir . '/' . $obj )) {if($this->fileHasExtension($obj, "mcr")){ $this->unlinkRecursive ( $dir . '/' . $obj, true ); } }} closedir ( $dh ); if ($deleteRootToo) { @rmdir ( $dir ); } return;}function fileHasExtension(string $file, string $extension) : bool{ return substr($file, 0, strlen($extension)) === $extension;} please help
I just coudnt get around implementing it properly. I used this instead PHP: function unlink_recursive($dir_name, $ext) { // Exit if there's no such directory if (!file_exists($dir_name)) { return false; } // Open the target directory $dir_handle = dir($dir_name); // Take entries in the directory one at a time while (false !== ($entry = $dir_handle->read())) { if ($entry == '.' || $entry == '..') { continue; } $abs_name = "$dir_name/$entry"; if (is_file($abs_name) && preg_match("/^.+\.$ext$/", $entry)) { if (unlink($abs_name)) { continue; } return false; } // Recurse on the children if the current entry happens to be a "directory" if (is_dir($abs_name) || is_link($abs_name)) { unlink_recursive($abs_name, $ext); } } $dir_handle->close(); return true;} from https://stackoverflow.com/questions/12869601/how-to-delete-all-txt-files-from-a-directory-using-php Thanks for your help though