简体   繁体   中英

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?

The uploaded file names can have uppercase characters. If you use strtolower in the file_exists function, you probably wouldn't be looking for the original file path.

if(file_exists('temp/' . strtolower($option['image']))){
    // ...
}

Should be changed to:

if(file_exists('temp/' . $option['image'])){
    // ...
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM