PHP's file_exists() will not work for me?
The file_exists()
function in PHP can be used to check if a file exists on the file system. However, if the file is located on a remote server or the file permission is not set correctly, the function may not be able to access the file and therefore will return false
. In that case, you can try using other functions like curl_exec()
or get_headers()
to check if the file exists or not.
Here's an example of how you can use file_exists
in PHP to check if a file exists and output the result:
<?php
$filename = "example.txt";
if (file_exists($filename)) {
echo "The file '$filename' exists." . PHP_EOL;
} else {
echo "The file '$filename' does not exist." . PHP_EOL;
}
In this code, the file_exists
function is used to check if the file example.txt
exists. If the file exists, the function returns true
, and the code inside the if
block is executed, echoing the message "The file 'example.txt' exists.". If the file does not exist, the function returns false
, and the code inside the else
block is executed, echoing the message "The file 'example.txt' does not exist.".
Here's another example of using file_exists
to check if a directory exists:
<?php
$dirname = "example_dir";
if (file_exists($dirname) && is_dir($dirname)) {
echo "The directory '$dirname' exists." . PHP_EOL;
} else {
echo "The directory '$dirname' does not exist." . PHP_EOL;
}
In this code, file_exists
is used to check if the directory example_dir
exists. If the directory exists, the function returns true
. The is_dir
function is used to check if the path specified by $dirname
is a directory. If $dirname
is a directory, the code inside the if
block is executed, echoing the message "The directory 'example_dir' exists.". If $dirname
is not a directory, the code inside the else
block is executed, echoing the message "The directory 'example_dir' does not exist.".