本篇文章给大家带来的内容是关于php文件处理函数的详细介绍(附示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
PHP可以很方便的对目录、文件进行操作,包括创建、读取、修改、删除等。
mkdir
bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] )尝试新建一个由 pathname 指定的目录。
mkdir 可以创建 pathname 指定目录,默认 mode 是0777,在 windows 下被忽略,失败返回 false。
rmdir
bool rmdir ( string $dirname [, resource $context ] )
尝试删除 dirname 所指定的目录。 该目录必须是空的,而且要有相应的权限。 失败时会产生一个 E_WARNING 级别的错误。如上所示,rmdir 可以删除目录,需要注意的是该目录必须为空,而且要有权限,失败返回 false。示例
立即学习“PHP免费学习笔记(深入)”;
file_put_contents
int file_put_contents ( string$filename, mixed$data[, int$flags= 0 [, resource$context]] )
和依次调用 fopen(),fwrite() 以及 fclose() 功能一样。file_put_contents 将 data 写入 filename 文件中,如果没有此文件,则创建,失败返回 false,成功返回写入字节数。示例
file_get_contents
string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )
和 file() 一样,只除了 file_get_contents() 把文件读入一个字符串。将在参数offset所指定的位置开始读取长度为maxlen的内容。file_get_cntents 读取 filename 中的内容,返回字符串,失败返回 false。示例
unlink
bool unlink ( string $filename [, resource $context ] )
删除 filename。和 Unix C 的 unlink() 函数相似。 发生错误时会产生一个 E_WARNING 级别的错误。unlink 删除 filename 文件,同样需要注意权限。示例
rename
bool rename ( string $oldname , string $newname [, resource $context ] )
尝试把 oldname 重命名为 newname。rename 不仅可以文件重命名,还可以移动文件,失败返回 false。示例
copy
bool copy ( string $source , string $dest [, resource $context ] )
将文件从 source 拷贝到 dest。如上所示,失败返回 false。示例
实例及注释
下面是几个实例,工作或面试中会用到。
'; foreach (scandir($path) as $line) { if ($line == '.' || $line == '..') { continue; } if (is_dir($path . '/' . $line)) { getAllFiles($path . '/' . $line); } echo '
注释
mkdir de 中的 recursive 参数,可以嵌套创建目录;
file_put_contents 中的 flags 参数,可以进行组合,详情参考链接;
file_put_contents 也可能返回等同于 false 的非布尔值,使用===判断;
file_get_contents 也可以打开 URL,获取网页内容;
file_get_contents 如果要打开有特殊字符的 URL (比如说有空格),就需要使用 urlencode() 进行 URL 编码;
copy 如果目标文件已存在,将会被覆盖;











