5-2 PHP文件系统之判断文件是否存在
本节编程练习不计算学习进度,请电脑登录imooc.com操作

PHP文件系统之判断文件是否存在

一般情况下在对文件进行操作的时候需要先判断文件是否存在,PHP中常用来判断文件存在的函数有两个is_file与file_exists.

$filename = './test.txt';
if (file_exists($filename)) {
    echo file_get_contents($filename);
}

如果只是判断文件存在,使用file_exists就行,file_exists不仅可以判断文件是否存在,同时也可以判断目录是否存在,从函数名可以看出,is_file是确切的判断给定的路径是否是一个文件。

$filename = './test.txt';
if (is_file($filename)) {
    echo file_get_contents($filename);
}

更加精确的可以使用is_readable与is_writeable在文件是否存在的基础上,判断文件是否可读与可写。

$filename = './test.txt';
if (is_writeable($filename)) {
    file_put_contents($filename, 'test');
}
if (is_readable($filename)) {
    echo file_get_contents($filename);
}

任务

判断如果$filename文件存在的话 就输出“文件存在”

  1. <?php
  2. $filename = '/data/webroot/usercode/code/resource/test.txt';
  3. //判断如果$filename文件存在的话 就输出文件内容
下一节