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:

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.

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:

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.

  • Was this tutorial helpful ?
  • YesNo