php 检查文件或目录是否存在代码总结
检查文件或目录是否存在,我们使用了php中常用的函数file_exists,这个函数就可以实现我想要的功能,下面是一个简单的检查文件是否存在的实例代码:
- <?php
- $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:\blabla\php"))
- {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;
- }
- @closedir($dir);
-
- $fp = @fopen($test_file, 'wb');
- if ($fp === false)
- {
- return $mark;
- }
- if (@fwrite($fp, 'directory access testing.') !== false)
- {
- $mark ^= 2;
- }
- @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;
- }
- @fclose($fp);
-
- $fp = @fopen($file_path, 'ab+');
- if ($fp && @fwrite($fp, '') !== false)
- {
- $mark ^= 6;
- }
- @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, "actions\data"));
- $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;
- }