1

We need to delete images created in linux file system. in a path /home/user/img/ (All images)

We have tried using unlink() but it is taking lot of time to delete it. Can someone help us how to delete images using linux commands must be passed with php script. I think rm command can do quickly but i am confused how to use

Our script:

$locationIMG_p="/home/user/img/";
$location_p="/home/user/img/";

$opend=opendir($locationIMG_p);

while(false!==($rf=readdir($opend)))
{           
    unlink($locationIMG_p.$rf);
}         

closedir($opend);
1
  • I can't see a command that is faster than unlink for what you want. You could potentially move the image to a temp folder and have a cronjob clear out that folder every hour or something, but I doubt that is faster =/ Commented Feb 18, 2012 at 11:15

2 Answers 2

4

Maybe try using shell command for this?

$cmd = "rm -f {$locationIMG_p}*"; exec($cmd);

But You must be very careful when using this ;)

//edit You should add some validation at path and use escapeshellarg

//edit2

Also You can try using DirectoryIterator as follows:

$di = new DirectoryIterator(path);
foreach($di as $file)
{
   if( $file->isFile() )
   {
        unlink($file->getPathname());
   }
}
Sign up to request clarification or add additional context in comments.

2 Comments

+1, Definitely fast and great solution to use it on a linux host (as Kiran)
Hi Bartosz ,Thanks, for replay
1
foreach(glob('/www/images/*.*') as $file)
    if(is_file($file))
        @unlink($file);

glob() returns a list of file matching a wildcard pattern.

unlink() deletes the given file name (and returns if it was successful or not).

The @ before PHP function names forces PHP to suppress function errors.

The wildcard depends on what you want to delete. *.* is for all files, while *.jpg is for jpg files. Note that glob also returns directories, so If you have a directory named images.jpg, it will return it as well, thus causing unlink to fail since it deletes files only.

is_file() ensures you only attempt to delete files.

Also read this for more details...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.