file_exists 方法检查文件或目录是否存在。它接受要检查的文件或目录的路径作为参数。以下是它的用途 -
当您需要在处理之前知道文件是否存在时,它非常有用。
这样,在创建新文件时使用此函数即可知道该文件是否已存在。
语法
file_exists($file_path)
参数
file_path - 设置要检查是否存在的文件或目录的路径。必需。
返回
file_exists() 方法返回。
- 如果文件或目录存在,则返回 True
- False,如果文件或目录不存在
示例
让我们看一个检查“candidate.txt”文件和即使文件不存在也显示一条消息。
实时演示
<?php
$myfile = '/doc/candidate.txt';
if (file_exists($myfile)) {
echo "$myfile exists!";
} else {
echo "$myfile does not exist!";
}
?>
以下是显示文件不存在的输出。
输出
/doc/candidate.txt does not exist!