Home Ask Login Register

Developers Planet

Your answer is one click away!

user3733831 February 2016

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()){
    } else {

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.


Ravi Hirani February 2016

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

Post Status

Asked in February 2016
Viewed 1,877 times
Voted 13
Answered 1 times


Leave an answer

Quote of the day: live life