简体   繁体   中英

Removing directory and its contents in php

I am trying to remove folders and its files and sub folders using php.

This is how I tried it.

$dir     = "../../images/$category_id/$delId"; 
$it      = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
foreach($files as $file) {
    if ($file->isDir()){
        rmdir($file->getRealPath());
    } else {
        unlink($file->getRealPath());
    }
}
rmdir($dir);

This is working on php 5.5+, but is doesn't work in php 5.2.17.

Can anybody tell me how I get it to work on 5.2 also. Thank you.

Use below code:-

function rrmdir($dir) { 
  foreach(glob($dir . '/*') as $file) { 
    if(is_dir($file)) rrmdir($file); else unlink($file); 
  } rmdir($dir); 
}

You can also simply do it by below statement:-

system('/bin/rm -rf ' . escapeshellarg($dir));

Hope it will help you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM