Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unlink/file_exists and file not found

I have this code in my application, often run in race condition by severals users of my application

clearstatcache(TRUE, $filepath);
if(file_exists($filepath)) unlink($filepath);

But, for this line of code, I still have severals errors each day like

unlink(file): No such file or directory

Server run Apache 2.2 and PHP 5.3.3. I know race problem, but think @ operator is just evil. I have first tried without any parameter for clearstatcache(), with the same error. How can I do it the correct way?

like image 343
Cédric Girard Avatar asked Apr 05 '11 08:04

Cédric Girard


2 Answers

you can try this

if(@unlink($path)) {
  echo "Deleted file "; 
}
else{
  echo "File can't be deleted";
}

I think it will be pretty fine;

like image 179
Headshota Avatar answered Oct 21 '22 10:10

Headshota


As said in comment, my need is to be sure I have deleted the file, not to know witch process delete it, so

@unlink($filepath);
clearstatcache(TRUE, $filepath);
if(file_exists($filepath)) throw new Exception('file not deleted : ' . $filepath);

may be a better way.

Thanks a lot for your help, it's so much easier to think another way to do it with severals comments.

like image 5
Cédric Girard Avatar answered Oct 21 '22 08:10

Cédric Girard