0

Possible Duplicate:
How do I recursively delete a directory and its entire contents (files+sub dirs) in PHP?
PHP: delete directory with files in it?

I am working with an site where I have to store four images of different formats by creating a directory in an specified folder. I have created the directory and inserted the images into it. Now my problem is I am unable to delete the directory with all the images.

Suppose I have,

$path = "offer_pic/";

$directory = $r2['shop_name'];

$realpath=$path.$directory.'/';

How do I delete all of the images inside $realpath, as well as the directory itself ($directory)?

Community
  • 1
  • 1
bid
  • 37
  • 1
  • 7

2 Answers2

5

This will do it, just be careful you don't delete the whole server:

$dir='your/directory';
exec('rm -rf '.escapeshellarg($dir));
Alasdair
  • 13,348
  • 18
  • 82
  • 138
  • 1
    Don't forget to escape `escapeshellarg($dir)` to be super duper safe. – Yzmir Ramirez Nov 12 '11 at 06:10
  • It should go without saying that this will only work on a *nix box. – nickb Nov 12 '11 at 06:14
  • Hi, Thanks for your response. Actually I have a directory called Offerspics inside which i have several directory like a, b, c, d. Now in Each directory i have 4 images. Now i am able to delete all images but after deleting the images i have to delete the particular directory also. As per Example, If I have to delete all images in directory a then i have to delete directory a also. – bid Nov 12 '11 at 06:15
  • Yes, that's what my code does. It deletes the directory and everything in it. – Alasdair Nov 12 '11 at 06:18
  • can you tell me how i should assign the path?? My Files are $realpath=$path.$directory.'/'; i have to delete all files under $directory and $directory also. – bid Nov 12 '11 at 06:25
  • `exec('rm -rf '.escapeshellarg($path.$directory));` – Alasdair Nov 12 '11 at 06:42
0

Well, sadly there is no method known to me at least without writing a loop to do the same. I'm more or less sure than O.S.s them self perform deletion of folders by first deleting files, expect they have a pre-defined subroutine to do it. (Like delTree in MS Dos to delete a folder and all files inside it).

My best option would be to use the below with piece of code into a function and simply call it passing the arguments as the folder name. Make those changes and you should have to do a simple call like delTree(C:\Program Files) to delete the entire folder. :)

$dir = 'your/directory/';
foreach(glob($dir.'*.*') as $v){
    unlink($v);
}
Rohan Durve
  • 340
  • 2
  • 14
  • Hi, Thanks for your response. Actually I have a directory called Offerspics inside which i have several directory like a, b, c, d. Now in Each directory i have 4 images. Now i am able to delete all images but after deleting the images i have to delete the particular directory also. As per Example, If I have to delete all images in directory a then i have to delete directory a also. – bid Nov 12 '11 at 06:16