码迷,mamicode.com
首页 > Web开发 > 详细

PHP -- 文件操作杂项

时间:2015-08-03 00:45:56      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

PHP – 文件操作杂项

PHP – 文件操作杂项

创建文件

用到的函数: basename, file_exists, touch

function createFile($filename) {
    // 验证文件名字是否合法
    $pattern = "/[\/, \*, <>, \?, \|]/";   // * 加不加 ‘\‘ 没影响, 因为 [] 里面只有 - 和 ^ 有特殊意义
    if (preg_match($pattern, basename($filename))) {
        return ‘非法文件名‘;
    } else {
        // 是否有同名文件
        if (file_exists($filename)) {
            return ‘文件存在‘;
        } else {
            if (touch($filename)) {      // chmod o+w  对目录有写权限
                return ‘创建成功‘;
            } else {
                return ‘创建失败‘;
            }
        }
    }
}

生成唯一的名字

$uniName = md5(uniqid(microtime(true), true));

mkdir 创建一个目录

$path = dirname(__FILE__).‘/upload/‘;
if (!file_exists($path)) {
    mkdir ($path, 0777, true);  // true 表示可以 递归创建 mkdir -p 的意思
    chmod ($path, 0777);        // 虽然上面设置了权限, 但 umask 有影响到
}

遍历目录

opendir, readdir, is_file, is_dir, closedir

function readDirectory($path) {
    if ($path[strlen($path)-1] == ‘/‘) {     // 去掉最后的斜线
        $path = substr($path, 0, -1);
    }

    $handle = opendir($path) or die (‘could not open file‘);
    while (($item = readdir($handle)) !== false) {
        if ($item == "." || $item == "..") {
            continue;
        }
        if (is_file($path.‘/‘.$item)) {      // is_file
            $arr[‘file‘][] = $item;
        }
        if (is_dir($path.‘/‘.$item)) {       // is_dir
            $arr[‘dir‘][] = $item;
        }
    }

    closedir($handle);
    return $arr;
}

scandir 返回当前目录下文件 ls

$files1 = scandir($dir);
$files2 = scandir($dir, 1);
Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

glob, 用统配符仅列出当前目录

foreach (glob("*.txt") as $filename) {
    echo $filename, ‘<br>‘;
}

funclist.txt
funcsummary.txt
quickref.txt

PHP -- 文件操作杂项

标签:

原文地址:http://www.cnblogs.com/sunznx/p/4696962.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!