Using PHP file_exists Function to Check File Existence
This article introduces PHP's file_exists function, explains its boolean return value, shows how to check both local and remote files with code examples, and highlights important considerations such as correct paths, permissions, and potential HTTP overhead.
In PHP we often need to verify whether a file exists before performing operations, and the language provides a convenient file_exists function for this purpose. This article explains how to use file_exists with examples.
The file_exists function accepts a file path as its argument and returns a boolean value: true if the file exists, false otherwise. The basic syntax is:
bool file_exists ( string $filename )The $filename parameter represents the path of the file to be checked.
A simple local‑file example:
<?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 is present the script outputs "文件存在。", otherwise it outputs "文件不存在。".
When using file_exists you must ensure that the file path is correct and that the script has read permission for that location.
Besides local paths, file_exists can also accept a URL to check a remote file. The following example demonstrates this:
<?php
$url = 'http://example.com/file.txt';
if (file_exists($url)) {
echo '远程文件存在。';
} else {
echo '远程文件不存在。';
}
?>Here a URL is passed to file_exists ; the script reports whether the remote file is reachable.
Note that when checking a remote file, file_exists performs an HTTP request to retrieve the file header, which can increase execution time if the server response is slow or the file is large.
Summary:
The PHP file_exists function is a useful tool for verifying the existence of files, both locally and remotely. It takes a file path (or URL) and returns a boolean indicating presence, helping developers avoid errors when performing file operations. Combine it with other file‑handling functions to write more robust PHP code.
We hope this guide helps readers understand and apply file_exists effectively; for further issues consult the official documentation or PHP community resources.
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.