PHP File Exists

Summary: this tutorial shows you how to check if a file exists using file_exists(), is_readable() and is_writable() functions.

PHP provides some functions that allow you to check if a file exists. Let’s examine those functions and how can we apply them in the script.

PHP file exists only

To check if a file exists, you use the the file_exist() function. This function returns TRUE if the file exists, otherwise it returns FALSE. Let’s take a look at the following example:

<?php $filename = './temp.txt'; if(file_exists($filename)){ echo sprintf('file %s exists',$filename); }else{ echo sprintf('file %s does not exist',$filename); }
Code language: HTML, XML (xml)

The script checks to see if the temp.txt file exists in the same folder with the script file.

PHP file exist and readable

To check whether a file exists and readable, you use the is_readable() function. The function returns TRUE if the file exists and is readable, otherwise it returns FALSE.

<?php $filename = './temp.txt'; if(is_readable($filename)){ echo sprintf('file %s exists and readable',$filename); }else{ echo sprintf('file %s does not exist or is not readable',$filename); }
Code language: HTML, XML (xml)

The is_readable() function should be used only if you want to open the file for reading.

PHP file exists and writable

In case you want to check if a file exists and is writable, you can use the is_writable() function. The function returns TRUE if the file exists and is writable, otherwise it returns FALSE.

The following example demonstrates how to use the is_writable() function:

<?php $filename = './temp.txt'; if(is_writable($filename)){ echo sprintf('file %s exists and writable',$filename); }else{ echo sprintf('file %s does not exist or is not writable',$filename); }
Code language: HTML, XML (xml)

The script checks whether the ./temp.txt file exists and is writable.

Notice that the file_exist(), is_readable() and is_writable() functions check not only if a file exists but also a folder exists.

Did you find this tutorial useful?