Mastering PHP’s file_exists: Check Local and Remote Files with Ease
Learn how to use PHP’s file_exists function to verify the existence of local and remote files, understand its syntax and return values, see practical code examples, and grasp important considerations such as correct paths and permission requirements.
In PHP, we often need to check whether a file exists before processing it. PHP provides the convenient file_exists function for this purpose.
The file_exists function takes a file path as its parameter and returns a boolean value indicating the file’s existence: true if the file exists, false otherwise. The basic syntax is: bool file_exists ( string $filename ) The $filename argument represents the path of the file to be checked.
Below is a simple example demonstrating how to use file_exists to check a local file:
<?php
$filename = 'test.txt';
if (file_exists($filename)) {
echo '文件存在。';
} else {
echo '文件不存在。';
}
?>In this example, we call file_exists with the path 'test.txt'. If the file exists, it outputs “文件存在”。 Otherwise, it outputs “文件不存在”。
When using file_exists, ensure that the file path is correct and that the script has read permissions for that path.
Besides checking local files, file_exists can also accept a URL to check a remote file. The following example shows how to verify a remote file’s existence:
<?php
$url = 'http://example.com/file.txt';
if (file_exists($url)) {
echo '远程文件存在。';
} else {
echo '远程文件不存在。';
}
?>Here we pass the URL 'http://example.com/file.txt' to file_exists. Note that checking a remote file triggers an HTTP request to fetch the file’s header, which may increase script execution time if the server response is slow or the file is large.
Summary
The PHP file_exists function is a useful tool for checking whether a file exists. It accepts a file path (or URL) and returns a boolean value. Using file_exists helps prevent errors when performing file operations, and can be combined with other file‑handling functions to write more robust PHP code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
