下面是一个简单的检查文件是否存在的实例代码:
复制代码 代码如下:
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>
如果文件存在,执行该 PHP 文件的显示结果是:
The file C:blablaphphello.txt exists.
如果文件不存在,执行该 PHP 文件的显示结果是:
The file C:blablaphphello.txt does not exist.
你也可以用file_exists 函数测试某个目录是否存在,示例代码如下:
复制代码 代码如下:
if (file_exists("C:blablaphp"))
{echo "yes";}
else
{echo "no";}
实例
复制代码 代码如下:
function file_mode_info($file_path)
{
if (!file_exists($file_path))
{
return false;
}
$mark = 0;
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN')
{
$test_file = $file_path . '/cf_test.txt';
if (is_dir($file_path))
{
$dir = @opendir($file_path);
if ($dir === false)
{
return $mark; //如果目录打开失败,直接返回目录不可修改、不可写、不可读
}
if (@readdir($dir) !== false)
{
$mark ^= 1; //目录可读 001,目录不可读 000
}
@closedir($dir);
$fp = @fopen($test_file, 'wb');
if ($fp === false)
{
return $mark; //如果目录中的文件创建失败,返回不可写。
}
if (@fwrite($fp, 'directory access testing.') !== false)
{
$mark ^= 2; //目录可写可读011,目录可写不可读 010
}
@fclose($fp);
@unlink($test_file);
$fp = @fopen($test_file, 'ab+');
if ($fp === false)
{
return $mark;
}
if (@fwrite($fp, "modify test.rn") !== false)
{
$mark ^= 4;
}
@fclose($fp);
if (@rename($test_file, $test_file) !== false)
{
$mark ^= 8;
}
@unlink($test_file);
}
elseif (is_file($file_path))
{
$fp = @fopen($file_path, 'rb');
if ($fp)
{
$mark ^= 1; //可读 001
}
@fclose($fp);
$fp = @fopen($file_path, 'ab+');
if ($fp && @fwrite($fp, '') !== false)
{
$mark ^= 6; //可修改可写可读 111,不可修改可写可读011...
}
@fclose($fp);
if (@rename($test_file, $test_file) !== false)
{
$mark ^= 8;
}
}
}
else
{
if (@is_readable($file_path))
{
$mark ^= 1;
}
if (@is_writable($file_path))
{
$mark ^= 14;
}
}
return $mark;
}
PHP判断目录是否存在
复制代码 代码如下:
function writeXmlFile($xmlData)
{
$time = time(); //获取时间戳,用于给文件命名
$path = dirname(__FILE__); //获取当前绝对路径
$path = substr_replace($path, "", stripos($path, "actionsdata")); //将此文件所在的固有路径替换成空
$path .= "xmlFiles"; //存放目录名
if(!is_dir($path))
{
mkdir($path); //新建目录
}
$filePathAndName = $path.$time.".xml";
$fp = fopen($filePathAndName, "w");
if(!$fp)
{
return false;
}
$flag = fwrite($fp, $xmlData);
if(!$flag)
{
return false;
}
fclose($fp);
return $filePathAndName;
}



