[SOLVED] php file_exists() only works once in the same function


This Content is from Stack Overflow. Question asked by Catie Camastro

I have a php function that renames two separate image files from a temporary to permanent path after first confirming that the temporary path exists.

When it checks for the fist file it works fine but, for some reason, the second file never passes the if(file_exists()) even though I can confirm with 100% certainty that the file path being checked does, in fact, exist.

The image files have different names but the codes are otherwise structured exactly the same so I can’t see why one would work and the other wouldn’t.

   $path1 = 'images/'.strtolower($option['image1']); // upload directory
   $tmp1 = 'temp/'.strtolower($option['image1']);
   if(rename($tmp1, $path1)){
      $error = 0;
      $error = 4;
   $path2 = 'images/'.strtolower($option['image2']); // upload directory
   $tmp2 = 'temp/'.strtolower($option['image2']); 
   if(rename($tmp2, $path2)){
     $error = 0;
     $error = 5;

Is there an issue with calling file_exists() twice? How else can I check for both paths?


The only two possibilities (if you’re absolutely sure the file path exists) I’m seeing are either 1.) a stat cache problem (you can clear the cache with clearstatcache) or 2.) a permission issue. Consider this:

$ touch /tmp/locked/file
$ php is_file_test.php
$ bool(true)
$ chmod -x /tmp/locked
$ php is_file_test.php
$ bool(false)

So it might be, that the parent directory of that file doesn’t have the x (executable) permission bit set. This prevents any process from iterating and accessing the directory’s content.

This Question was asked in StackOverflow by Catie Camastro and Answered by marco-a It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?