php Editor Banana today will introduce to you how to use the PHP programming language to check whether a file or directory exists. When developing a website or application, sometimes you need to check whether a specific file or directory exists so that you can act accordingly. We can easily implement this function through the file system functions provided by PHP. This article will introduce in detail how to use PHP's file_exists() function and is_dir() function to check the existence of a file or directory, helping you better master PHP file system operation skills.
Use PHP to check if a file or directory exists
Inphp, checking whether a file or directory exists is a common task. There are several ways to accomplish this:
file_exists() function
file_exists()
The function checks whether the specified file exists and returns a Boolean value (true
means it exists,false
means it does not exist).
if (file_exists("path/to/file.txt")) { // file exists } else { // file does not exist }
is_file() function
is_file()
The function checks whether the specified path is an ordinary file and returns a Boolean value (true
means it is a file,false
means it is not a file).
if (is_file("path/to/file.txt")) { // is a file } else { // Not a file }
isdir() function
isdir()
The function checks whether the specified path is a directory and returns a Boolean value (true
means it is a directory,false
means it is not a directory).
if (isdir("path/to/directory")) { // is a directory } else { // Not a directory }
filemtime() function
filemtime()
The function returns the last modified timestamp of the specified file. If the file does not exist, returnsfalse
.
if (filemtime("path/to/file.txt")) { // file exists } else { // file does not exist }
fileatime() function
fileatime()
The function returns the timestamp of the last access of the specified file. If the file does not exist, returnsfalse
.
if (fileatime("path/to/file.txt")) { // file exists } else { // file does not exist }
pathinfo() function
pathinfo()
The function returns information about the file patharray, including whether the file exists.
$path_info = pathinfo("path/to/file.txt"); if ($path_info["dirname"] && $path_info["basename"]) { // file exists } else { // file does not exist }
glob() function
glob()
The function returns an array of files and directories that match the specified pattern. If there is no match, an empty array is returned.
$files = glob("path/to/files/*"); if ($files) { //The file or directory exists } else { //The file or directory does not exist }
Best Practices
realpath()
function to resolve symbolic links to ensure that the actual file or directory is being checked.file_exists()
function as a shortcut to other checks as it is the fastest.The above is the detailed content of PHP check if file or directory exists. For more information, please follow other related articles on the PHP Chinese website!