Check if a file exists in PHP
During coding, sometimes we need to check if a file exists in a given directory or not before processing it using PHP. So, today we will explain to you how to check if a file exists or not in PHP.
PHP Checking if a file exists in a directory, How to check if file exists in PHP, Checking whether a file exists, php file exists relative path, check if file exists in a folder php, php delete file if exists, check any file exists in folder in php, how to verify if a file exists in php, How to check if file exists and readable in PHP, How to check if file exists and writable in PHP, How to check if file exists and executable in PHP
Checkout more articles on PHP
The four different ways to check a file exists or not
1. file_exists()
Using the file_exists() function, you can check whether a file or directory exists or not. But this function works with the path of the file or directory not works with HTTP URLs. It returns true if the file exists otherwise false. Let’s take an example.
1 2 3 4 5 6 7 8 9 | <?php $filename = './text.txt'; if (file_exists($filename)) { echo "The file $filename exists"; } else { echo "The file $filename does not exist"; } ?> |
2. is_readable()
The is_readable() function is used to check whether a file or directory exists and is readable or not. You can use this function, when you need to open a file for reading. We need to pass file or directory path as parameter to is_readable()
function. It returns true if the file exists and readable otherwise false.
1 2 3 4 5 6 7 8 9 | <?php $filename = './text.txt'; if (is_readable($filename)) { echo "The file $filename exists and readable"; } else { echo "The file $filename does not exist or not readable"; } ?> |
No need to use file_exists()
and is_readable()
functions together because the is_readable()
function will check file_exists()
as well.
You can use is_file()
or is_dir()
with is_readable()
to check if it is readable specifically on a file only or specifically on a directory only.
3. is_writable()
By the use of the is_writable() function, you can check whether a file or directory exists and writable or not. It returns true if the file exists and writable otherwise false.
1 2 3 4 5 6 7 8 9 | <?php $filename = './text.txt'; if (is_writable($filename)) { echo "The file $filename exists and writable"; } else { echo "The file $filename does not exist or not writable"; } ?> |
4. is_executable()
Using the is_executable() function, you can check whether a file or directory exists and executable or not. It returns true if the file exists and executable otherwise false.
1 2 3 4 5 6 7 8 9 | <?php $filename = './text.txt'; if (is_executable($filename)) { echo "The file $filename exists and executable"; } else { echo "The file $filename does not exist or not executable"; } ?> |
That’s it for today.
Thank you for reading. Happy Coding..!!