note 69375 deleted from function.file-exists by colder
| From: | colder@php.net | Date: | Sat, 02 Sep 2006 23:08:18 +0000 |
| Subject: | note 69375 deleted from function.file-exists by colder | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-116642@lists.php.net to get a copy of this message | ||
Note Submitter: info at g2data dot com
Reason: in docs
----
You'd think such a simple test would be simple, but oh no.
I found that sometimes file_exists can return true when a file does NOT exist. But there is a
reason for this (as I finally found):
I used the following script to test this problem I was having on PHP5.x on Debian Sarge, Ubuntu
Hoary & Windows.
On Ubuntu & Sometimes Windows, the script continued to say $doc existed even though it
definitely did not.
<?php
$doc = 'tmp/test.doc';
if (!is_dir('tmp')) {
mkdir('tmp'); // create a tmp dir if it doesn't already exist
}
touch($doc); // Create a doc
if (file_exists($doc)) { // test if file exists:
echo "file_exists function returned: TRUE ". $doc ." EXISTS:<br />";
} else {
echo $doc ." Don't Exists<br />";
}
// manually confirm file exists by examining the output of the system DIR/ls (depending on your OS)
echo "<pre>PRE rm: ". $doc ."<br />";
echo system(($_ENV['OS']? 'DIR tmp':'ls tmp'));
echo "</pre>";
// Now issue a system command to DEL/rm the doc you created (depending on your OS)
exec(($_ENV['OS']? 'DEL "'. str_replace('/','\\',$doc)
.'"':'rm "'. $doc .'"'));
// Now look at output from a system DIR/ls of the tmp dir. It should show no sign of test.doc
anymore.
echo "<pre>POST rm: ". $doc ."<br />";
echo system(($_ENV['OS']? 'DIR tmp':'ls tmp'));
echo "</pre>";
// now test for the existance of $doc.
if (file_exists($doc)) {
echo "file_exists function returned: TRUE ". $doc ." <strong>STILL
EXISTS!!!</strong><br />";
} else {
echo $doc ." DELETED<br />";
}
// On Ubuntu and occasionally the windows box, this test would return true for the second test,
despite the fact we had without doubt deleted $doc prior to this second file_exists($doc) test.
?>
After much head scratching I discovered the answer to this problem is to use:
clearstatcache();
If you change the contents of a file/dir in some way just prior to using file_exists (and others
shown below), file_exists returns the value of what's in the statcache, which might not reflect
the whole truth.
To avoid getting a true, when it should be a false, use clearstatcache prior to your test.
Affected functions include: stat(), lstat(), file_exists(), is_writable(), is_readable(),
is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(),
filegroup(), fileowner(), filesize(), filetype(), and fileperms().