phpfile-renamefile-exists

php file_exists() only works once in the same function


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.

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

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

Edit As per Marco-A's suggestion, I added clearstatcache(); between the two if/then blocks and it worked like a charm.


Solution

  • 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.