6.1 Checking Whether a File Exists


You want to know whether a file exists before you try to perform any operations involving it.

Technique

Use the file_exists() function, which will return true ( 1 ) if the file exists and false ( ) if the file does not exist:

 <?php $fn = "/home/designmm/public_html/favorite_sites.info"; if (!file_exists($fn)) {     die("File $fn does not exist"); } $fp = @fopen ($fn, 'a')   or die ("Cannot open $fn for append access"); // Add a favorite site to the list fputs ($fp, "http://www.zend.com/\n"); @fclose ($fp); ?> 

Comments

In this example, we simply use file_exists() to check whether the specified file exists. The file_exists() function is a slow function due to the fact that it must perform a stat() on the file in question. Therefore, the results are cached for the duration of the script's execution. The following is an example in which file_exists() will not work as expected:

 <?php $fn = "/usr/local/files/somefile.txt"; if  (!file_exists ($fn)) {     $fp = fopen($fn, "w"); } if (file_exists ($fn)) {     echo "The File exists"; } ?> 

If you run this script, you will notice that no output is sent (if the file does not exist, and in this case it doesn't). The reason is that the results of the first file_exists() function call have already been cached into memory, so the second time file_exists() is called, nothing will change. It is the same as doing the following:

 <?php $fn = "/usr/local/somefiles/"; $exists = file_exists ($fn); if (!$exists) {     $fp = fopen ($fn, "w"); } if ($exists) {      print "The File Exists"; } ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net