本文介绍了 PHP 文件的相关函数。本文只是部分列举,详情请查看官方文档。
读取文件最后一行
1 | $pos = -2; //偏移量 |
HTML 上传文件
1 | <form action="url" method="post" enctype="multipart/form-data"> |
PHP 会将文件存到临时文件中,脚本结束就会销毁,所以必须存到另外的位置。
1 | $file = $_FILE['file']; |
获取路径
执行命令所在路径
getcwd()文件所在路径
__FILE__文件所在目录路径
__DIR__dirname(__FILE__)
目录相关函数
1 | resource opendir( string $path [, resource $context ] ) |
打开一个目录句柄,可用于之后的 closedir() readdir() rewinddir()。
1 | if (is_dir($dir)) { |
readdir()从目录句柄中读取条目。chdir()改变目录chroot()改变根目录closedir()关闭目录句柄dir()返回一个Directory类实例
1 | $d=dir($path); |
getcwd()取得当前工作目录rewinddir()倒回目录句柄scandir()列出指定路径中的文件和目录
1 | array scandir ( string $directory [, int $sorting_order [, resource $context ]] ) |
返回包含文件和目录的数组。
SPL
SplFileInfo
1 | $file = SplFileInfo('file'); |
SplFileObject
1 | $file = new SplFileObject($file_name [, $open_mode, $use_include_path, $context]) |
文件操作相关函数
更改权限
chgrp()chmod()chown()复制
copy()删除
unlink()unset()判断
is_dir()is_file()is_executable()is_link()
读写文件
官方文档:http://php.net/manual/zh/function.file-get-contents.php
file_get_contents($filePath)
file_put_contents($filePath, $content) 可以通过设置第三个参数,将内容追加,而不是覆盖。
官方文档:http://php.net/manual/zh/function.stream-get-contents.php
stream_get_contents($resource) 读取资源流到一个字符串
stream_context_create($array) 创建资源流上下文,参数必须为 关联数组
官方文档:http://php.net/manual/zh/function.fopen.php
1 | $fh = fopen($filePath, $mode); |