PHP - 文件存在


在对文件执行任何处理之前,首先检查您尝试打开的文件是否真的存在通常很方便。否则,程序可能会引发运行时异常。

PHP 内置库在这方面提供了一些实用功能。我们将在本章中讨论的一些功能是 -

函数 描述
file_exists() 测试文件是否存在
is_file() 如果 fopen() 返回的句柄引用文件或目录。
is_readable() 测试打开的文件是否允许读取数据
is_writable() 测试是否允许在文件中写入数据

file_exists() 函数

此函数适用于文件和目录。它检查给定的文件或目录是否存在。


 file_exists(string $filename): bool

此函数的唯一参数是一个字符串,表示具有完整路径的文件/目录。该函数根据文件是否存在返回 true false

例子

以下程序检查文件 “hello.txt” 是否存在。


<?php
   $filename = 'hello.txt';
   if (file_exists($filename)) {
      $message = "The file $filename exists";
   } else {
      $message = "The file $filename does not exist";
   }
   echo $message;
?>

如果当前目录中确实存在该文件,则消息为 -

The file hello.txt exists

否则,消息为 -

The file hello.txt does not exist

例子

指向文件的字符串可能具有相对或绝对路径。假设 “hello.txt” 文件在当前目录内的 “hello” 子目录中可用。


<?php
   $filename = 'hello/hello.txt';
      if (file_exists($filename)) {
   $message = "The file $filename exists";
   } else {
      $message = "The file $filename does not exist";
   }
   echo $message;
?>

它将产生以下输出 -

The file hello/hello.txt exists

例子

尝试给出绝对路径,如下所示 -


<?php
   $filename = 'c:/xampp/htdocs/hello.txt';
   if (file_exists($filename)) {
      $message = "The file $filename exists";
   } else {
      $message = "The file $filename does not exist";
   }
   echo $message;
?>

它将产生以下输出 -

The file c:/xampp/htdocs/hello.txt exists

is_file() 函数

file_exists() 函数对现有文件和目录返回 trueis_file() 函数可帮助您确定它是否为文件。


 is_file ( string $filename ) : bool

以下示例显示了 is_file() 函数的工作原理 -


<?php
   $filename = 'hello.txt';

   if (is_file($filename)) {
      $message = "$filename is a file";
   } else {
      $message = "$filename is a not a file";
   }
   echo $message;
?>

输出表明它是一个文件 -

hello.txt is a file

现在,将 “$filename” 更改为目录,并查看结果 -


<?php
   $filename = hello;

   if (is_file($filename)) {
      $message = "$filename is a file";
   } else {
      $message = "$filename is a not a file";
   }
   echo $message;
?>

现在,您将被告知 “hello” 不是一个文件。

请注意,is_file() 函数接受 $filename,并且仅当 $filename 是文件且存在时才返回 true

is_readable() 函数

有时,您可能希望事先检查是否可以读取文件。is_readable() 函数可以确定这一事实。


 is_readable ( string $filename ) : bool

例子

下面给出了 is_readable() 函数如何工作的示例 -


<?php
   $filename = 'hello.txt';
   if (is_readable($filename)) {
      $message = "$filename is readable";
   } else {
      $message = "$filename is not readable";
   }
   echo $message;
?>

它将产生以下输出 -

hello.txt is readable

is_writable() 函数

您可以使用 is_writable() 函数来检查文件是否存在以及是否可以对给定文件执行写入操作。


 is_writable ( string $filename ) : bool

例子

以下示例显示了 is_writable() 函数的工作原理 -


<?php
   $filename = 'hello.txt';

   if (is_writable($filename)) {
      $message = "$filename is writable";
   } else {
      $message = "$filename is not writable";
   }
   echo $message;
?>

对于普通的存档文件,程序会告知它是可写的。但是,将其属性更改为 “read_only” 并运行该程序。您现在可以获得 -

hello.txt is writable