- PHP File Exists
- Check if a file exists using the file_exists() function
- Check if a file exists using the is_file() function
- Check if a file exists and readable
- Check if a file exists and writable
- Summary
- file_exists
- Return Values
- Errors/Exceptions
- Examples
- Notes
- See Also
- User Contributed Notes 31 notes
- PHP code to create a file
- PHP Create a File Example
- Create a file if it doesn’t exist in PHP
PHP File Exists
Summary: in this tutorial, you will learn how to check if a file exists in PHP using the file_exists() , is_file() , is_readable() , and is_writable() functions.
PHP provides some useful functions that allow you to check if a file exists. Let’s examine these functions and how to use them effectively.
Check if a file exists using the file_exists() function
To check if a file exists, you use the file_exist() function:
file_exists ( string $filename ) : bool
Code language: PHP (php)
The file_exists() function accepts a filename and returns true if the file exists; otherwise it returns false .
The following example uses the file_exists() function to check if the file readme.txt exists in the current directory:
$filename = 'readme.txt'; if (file_exists($filename)) < $message = "The file $filename exists"; > else < $message = "The file $filename does not exist"; > echo $message;
Code language: HTML, XML (xml)
If the readme.txt exists in the same directory of the script, you’ll see the following message:
The file readme.txt exists
Code language: CSS (css)
…otherwise, you’ll see a different message:
The file readme.txt does not exist
Code language: CSS (css)
Note that the $filename can be also a path to a directory. In this case, the file_exists() function returns true if the directory exists.
Check if a file exists using the is_file() function
If you want to check if a path is a file (not a directory) and exists in the file system, you can use the is_file() function.
The is_file() function accepts a $filename and returns true if the $filename is a file and exists:
is_file ( string $filename ) : bool
Code language: PHP (php)
The following example uses the is_file() function to check if the file readme.txt exists:
$filename = 'readme.txt'; if (is_file($filename)) < $message = "The file $filename exists"; > else < $message = "The file $filename does not exist"; > echo $message;
Code language: HTML, XML (xml)
Check if a file exists and readable
In practice, you often want to check if a file exists before reading its contents. To check if a file exists and is readable, you use the is_readable() function:
is_readable ( string $filename ) : bool
Code language: PHP (php)
The is_readable() function returns true if the $filename exists and readable, or false otherwise. Note that the $filename can be a directory.
The following example uses the is_readable() function to check if the readme.txt file exists and readable:
$filename = 'readme.txt'; if (is_readable($filename)) < $message = "The file $filename exists"; > else < $message = "The file $filename does not exist"; > echo $message;
Code language: HTML, XML (xml)
Check if a file exists and writable
Before writing to a file, you need to check the file exists and is writable. In this case, you can use the is_writable() function:
is_writable ( string $filename ) : bool
Code language: PHP (php)
The is_writable() function returns true if the $filename exists and writable, or false otherwise.
The following example uses the is_writable() function to check the readme.txt file exists and writable:
$filename = 'readme.txt'; if (is_writable($filename)) < $message = "The file $filename exists"; > else < $message = "The file $filename does not exist"; > echo $message;
Code language: HTML, XML (xml)
Summary
- Use the file_exists() function to check if a file exists.
- Use the is_file() function to check if a path is a regular file, not a directory, and that file exists.
- Use the is_readable() function to check if a file exists and readable.
- Use the is_writable() function to check if a file exists and writable.
file_exists
On windows, use //computername/share/filename or \\computername\share\filename to check files on network shares.
Return Values
Returns true if the file or directory specified by filename exists; false otherwise.
Note:
This function will return false for symlinks pointing to non-existing files.
Note:
The check is done using the real UID/GID instead of the effective one.
Note: Because PHP’s integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.
Errors/Exceptions
Upon failure, an E_WARNING is emitted.
Examples
Example #1 Testing whether a file exists
if ( file_exists ( $filename )) echo «The file $filename exists» ;
> else echo «The file $filename does not exist» ;
>
?>
Notes
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
See Also
- is_readable() — Tells whether a file exists and is readable
- is_writable() — Tells whether the filename is writable
- is_file() — Tells whether the filename is a regular file
- file() — Reads entire file into an array
- SplFileInfo
User Contributed Notes 31 notes
Note: The results of this function are cached. See clearstatcache() for more details.
That’s a pretty big note. Don’t forget this one, since it can make your file_exists() behave unexpectedly — probably at production time 😉
Note that realpath() will return false if the file doesn’t exist. So if you’re going to absolutize the path and resolve symlinks anyway, you can just check the return value from realpath() instead of calling file_exists() first
I needed to measure performance for a project, so I did a simple test with one million file_exists() and is_file() checks. In one scenario, only seven of the files existed. In the second, all files existed. is_file() needed 3.0 for scenario one and 3.3 seconds for scenario two. file_exists() needed 2.8 and 2.9 seconds, respectively. The absolute numbers are off course system-dependant, but it clearly indicates that file_exists() is faster.
file_exists() does NOT search the php include_path for your file, so don’t use it before trying to include or require.
Yes, include does return false when the file can’t be found, but it does also generate a warning. That’s why you need the @. Don’t try to get around the warning issue by using file_exists(). That will leave you scratching your head until you figure out or stumble across the fact that file_exists() DOESN’T SEARCH THE PHP INCLUDE_PATH.
file_exists() is vulnerable to race conditions and clearstatcache() is not adequate to avoid it.
The following function is a good solution:
function file_exists_safe ( $file ) if (! $fd = fopen ( $file , ‘xb’ )) return true ; // the file already exists
>
fclose ( $fd ); // the file is now created, we don’t need the file handler
return false ;
>
?>
The function will create a file if non-existent, following calls will fail because the file exists (in effect being a lock).
IMPORTANT: The file will remain on the disk if it was successfully created and you must clean up after you, f.ex. remove it or overwrite it. This step is purposely omitted from the function as to let scripts do calculations all the while being sure the file won’t be «seized» by another process.
NOTE: This method fails if the above function is not used for checking in all other scripts/processes as it doesn’t actually lock the file.
FIX: You could flock() the file to prevent that (although all other scripts similarly must check it with flock() then, see https://www.php.net/manual/en/function.flock.php). Be sure to unlock and fclose() the file AFTER you’re done with it, and not within the above function:
function create_and_lock ( $file ) if (! $fd = fopen ( $file , ‘xb’ )) return false ;
>
if (! flock ( $fd , LOCK_EX | LOCK_NB )) < // may fail for other reasons, LOCK_NB will prevent blocking
fclose ( $fd );
unlink ( $file ); // clean up
return false ;
>
return $fd ;
>
if ( $lock = create_and_lock ( «foo.txt» )) // do stuff
flock ( $fd , LOCK_UN ); // unlock
fclose ( $fd ); // close
>
?>
SEE ALSO: https://linux.die.net/man/2/open about O_CREAT|O_EXCL (which is used with the ‘x’ modifier for fopen()) and problems with NFS
In response to seejohnrun’s version to check if a URL exists. Even if the file doesn’t exist you’re still going to get 404 headers. You can still use get_headers if you don’t have the option of using CURL..
$file = ‘http://www.domain.com/somefile.jpg’;
$file_headers = @get_headers($file);
if($file_headers[0] == ‘HTTP/1.1 404 Not Found’) $exists = false;
>
else $exists = true;
>
I was having problems with the file_exists when using urls, so I made this function:
function file_exists_2 ( $filePath )
return ( $ch = curl_init ( $filePath )) ? @ curl_close ( $ch ) || true : false ;
>
?>
Cheers!
If you are trying to access a Windows Network Share you have to configure your WebServer with enough permissions for example:
You will get an error telling you that the pathname doesnt exist this will be because Apache or IIS run as LocalSystem so you will have to enter to Services and configure Apache on «Open a session as» Create a new user that has enough permissions and also be sure that target share has the proper permissions.
Hope this save some hours of research to anyone.
With PHP 7.0 on Ubuntu 17.04 and with the option allow_url_fopen=On, file_exists() returns always false when trying to check a remote file via HTTP.
returns always «missing», even for an existing URL.
I found that in the same situation the file() function can read the remote file, so I changed my routine in
This is clearly a bit slower, especially if the remote file is big, but it solves this little problem.
here a function to check if a certain URL exist:
function url_exists ( $url ) $a_url = parse_url ( $url );
if (!isset( $a_url [ ‘port’ ])) $a_url [ ‘port’ ] = 80 ;
$errno = 0 ;
$errstr = » ;
$timeout = 30 ;
if(isset( $a_url [ ‘host’ ]) && $a_url [ ‘host’ ]!= gethostbyname ( $a_url [ ‘host’ ])) $fid = fsockopen ( $a_url [ ‘host’ ], $a_url [ ‘port’ ], $errno , $errstr , $timeout );
if (! $fid ) return false ;
$page = isset( $a_url [ ‘path’ ]) ? $a_url [ ‘path’ ]: » ;
$page .= isset( $a_url [ ‘query’ ])? ‘?’ . $a_url [ ‘query’ ]: » ;
fputs ( $fid , ‘HEAD ‘ . $page . ‘ HTTP/1.0’ . «\r\n» . ‘Host: ‘ . $a_url [ ‘host’ ]. «\r\n\r\n» );
$head = fread ( $fid , 4096 );
fclose ( $fid );
return preg_match ( ‘#^HTTP/.*\s+[200|302]+\s#i’ , $head );
> else return false ;
>
>
?>
in my CMS, I am using it with those lines:
if(!isset( $this -> f_exist [ $image ][ ‘exist’ ]))
if( strtolower ( substr ( $fimage , 0 , 4 )) == ‘http’ || strtolower ( substr ( $fimage , 0 , 4 )) == ‘www.’ ) if( strtolower ( substr ( $image , 0 , 4 )) == ‘www.’ ) $fimage = ‘http://’ . $fimage ;
$image = ‘http://’ . $image ;
>
$this -> f_exist [ $image ][ ‘exist’ ] = $this -> url_exists ( $fimage ); //for now
> else $this -> f_exist [ $image ][ ‘exist’ ] = ( $fimage != » && file_exists ( $fimage ) && is_file ( $fimage ) && is_readable ( $fimage ) && filesize ( $fimage )> 0 );
>
>
?>
I wrote this little handy function to check if an image exists in a directory, and if so, return a filename which doesnt exists e.g. if you try ‘flower.jpg’ and it exists, then it tries ‘flower[1].jpg’ and if that one exists it tries ‘flower[2].jpg’ and so on. It works fine at my place. Ofcourse you can use it also for other filetypes than images.
function imageExists ( $image , $dir )
PHP code to create a file
This article is created to cover multiple scripts or programs in PHP to create a file. To create a file in PHP, use any of the following modes:
The last four modes, which are x, x+, c, and c+, only create a new file if the specified file does not exit.
PHP Create a File Example
Here is a snapshot of the folder before executing the PHP script to create a file:
Now the PHP script to create a new file is:
The output of the above PHP example is:
After running the above PHP script to make a new file, here is a snapshot of the same folder (the current directory):
Note: The fopen() function opens a file. And with the «w» mode given to this function, it creates a new file and then opens that file.
Create a file if it doesn’t exist in PHP
This section is created to cover a program in PHP that creates a new file only if the specified file does not exist.
The x mode is used when we need to create a file only if the specified file does not exist. For example:
Since the file codescracker.txt already exists in the current directory. Therefore, the output produced by the above PHP example is:
The same program can also be created in this way:
To hide the default error message, use the @ character before the fopen() function. For example:
Now the output produced by the above PHP example is:
Let me tell you again: if the specified file does not exist, a new one with the specified name will get created. For example, let me create another example in which I will provide the name of a file that does not exist in the current directory:
Since the file temp.txt is not available in the current directory, it will be created, and the output produced by the above PHP example should be «The file created successfully!»
Liked this article? Share it!