Home  >  Article  >  Backend Development  >  Summary of PHP file functions and directory functions

Summary of PHP file functions and directory functions

巴扎黑
巴扎黑Original
2017-08-18 13:24:501478browse

The following editor will bring you an article based on common file functions and directory functions in PHP. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

1. Commonly used file function libraries

1. basename(); -- Return the filename portion of the path.


string basename ( string $path [, string $suffix ] )
//给出一个包含有指向一个文件的全路径的字符串,本函数返回基本的文件名。  

Parameters: path A path. In Windows, both slash (/) and backslash (\) can be used as directory separators. In other environments it is a slash (/)

suffix If the file name ends with suffix, this part will also be removed.

Return value: Return the basic file name of path.


$path = 'd:/test/test.txt';

echo basename($path);
echo "<br>";
echo basename($path,&#39;.txt&#39;);

2. dirname(); -- Return the directory part of the path


string dirname ( string $path )
//给出一个包含有指向一个文件的全路径的字符串,本函数返回去掉文件名后的目录名。 

Parameters: path, a path. In Windows, both slash (/) and backslash (\) can be used as directory separators. In other circumstances it is a slash (/).

Return value: Returns the parent directory of path. If there are no slashes in path, a dot ('.') is returned, indicating the current directory. Otherwise, the string returned is the string after removing the /component at the end of the path (the last slash and the following parts).


$path = &#39;d:/test/test.txt&#39;;

echo basename($path);
echo "<br>";
echo basename($path,&#39;.txt&#39;);
echo "
"; echo dirname($path);

3. pathinfo(); --Return file path information


mixed pathinfo ( string $path [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] )
//pathinfo() 返回一个关联数组包含有 path 的信息。返回关联数组还是字符串取决于 options。  

Parameters: path The path to be parsed.​

options If specified, the specified elements will be returned; they include: PATHINFO_DIRNAME, PATHINFO_BASENAME and PATHINFO_EXTENSION or PATHINFO_FILENAME. If options are not specified, the default is to return all units.

Return value: If options are not passed in, an array containing the following units will be returned: dirname, basename and extension (if any), and filename.


$path = &#39;d:/test/test.txt&#39;;
var_dump(pathinfo($path));

4. filetype();--Get the file type


string filetype ( string $filename )
//返回文件的类型。

Parameters: filename The path to the file.

Return value: Return the type of file.

Possible values ​​are fifo, char, dir, block, link, file and unknown. Returns FALSE if an error occurs. filetype() also generates an E_NOTICE message if the stat call fails or the file type is unknown.


$path = &#39;d:/test/test.txt&#39;;
echo filetype($path);
//结果file

5, fstat() and stat();

##⑴, fstat ()-Get file information through the opened file pointer


array fstat ( resource $handle )
//获取由文件指针 handle 所打开文件的统计信息。本函数和 stat() 函数相似,除了它是作用于已打开的文件指针而不是文件名。

Parameters: handle file system pointer, Is a resource typically created by fopen().

Return value: Returns an array with the statistical information of the file. The format of the array is detailed in the stat() page of the manual.

⑵、stat() --gives the file information


array stat ( string $filename )
//获取由 filename 指定的文件的统计信息。如果 filename 是符号连接,则统计信息是关于被连接文件本身的,而不是符号连接。
//lstat() 和 stat() 相同,只除了它会返回符号连接的状态。

Parameter: filename The path of the file.


$path = &#39;d:/test/test.txt&#39;;

$fp = fopen("d:/test/test.txt","r");
$fstat = fstat($fp);
fclose($fp);
var_dump($fstat);

6. filesize();--Get the file size


int filesize ( string $filename )
//取得指定文件的大小。

Parameters: filename The path to the file.

Return value: Returns the number of bytes of the file size. If an error occurs, it returns FALSE and generates an E_WARNING level error.


<?php

// 输出类似:test.txt:  bytes

$filename = &#39;d:/test/test.txt&#39;;
echo $filename . &#39;: &#39; . filesize($filename) . &#39; bytes&#39;;

?>
//结果:d:/test/test.txt: 12 bytes

7. disk_free_space(); -- Returns the available space in the directory


float disk_free_space ( string $directory )
//给出一个包含有一个目录的字符串,本函数将根据相应的文件系统或磁盘分区返回可用的字节数。 

Parameters: directory file system directory or disk partition.


header("Content-Type:Text/html;charset=utf8");
$path = &#39;d:/test/test.txt&#39;;
$df = disk_free_space("d:/");
echo $df."字节";

8. disk_total_space(); --Returns the total disk size of a directory


float disk_total_space ( string $directory )
//给出一个包含有一个目录的字符串,本函数将根据相应的文件系统或磁盘分区返回所有的字节数。 【译者注】本函数返回的是该目录所在的磁盘分区的总大小,因此在给出同一个磁盘分区的不同目录作为参数所得到的结果完全相同。 在 Unix 和 Windows 200x/XP 中都支持将一个磁盘分区加载为一个子目录,这时正确使用本函数就很有意义。

Parameters: directory The directory or disk partition of the file system

9, fopen( $filepath,$mode) 


resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )
//fopen() 将 filename 指定的名字资源绑定到一个流上  

参数:filename 如果 filename 是 "scheme://..." 的格式,则被当成一个 URL,PHP 将搜索协议处理器(也被称为封装协议)来处理此模式。如果该协议尚未注册封装协议,PHP 将发出一条消息来帮助检查脚本中潜在的问题并将 filename 当成一个普通的文件名继续执行下去。

fopen() <span style="font-family:NSimsun">mode</span> 的可能值列表
<span style="color:#000000;font-size:16px;font-family:NSimsun">mode</span> 说明
'r' 只读方式打开,将文件指针指向文件头。
'r+' 读写方式打开,将文件指针指向文件头。
'w' 写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。
'w+' 读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。
'a' 写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。
'a+' 读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。
'x' 创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 <span style="font-family:NSimsun">FALSE</span>,并生成一条 <span style="font-family:NSimsun">E_WARNING</span> 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。
'x+' 创建并以读写方式打开,其他的行为和 'x' 一样。


<?php
$handle = fopen("/home/rasmus/file.txt", "r");
$handle = fopen("/home/rasmus/file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:password@example.com/somefile.txt", "w");
?>

10、file();--把整个文件读入一个数组中


array file ( string $filename [, int $flags = 0 [, resource $context ]] )
//把整个文件读入一个数组中。 

参数:filename 文件的路径。

flags 可选参数 flags 可以是以下一个或多个常量:

1、FILE_USE_INCLUDE_PATH 在 include_path 中查找文件。

2、FILE_IGNORE_NEW_LINES 在数组每个元素的末尾不要添加换行符

3、FILE_SKIP_EMPTY_LINES 跳过空行。

context 一个上下文资源,创建stream_context_create()函数。


<?php
// 将一个文件读入数组。本例中通过 HTTP 从 URL 中取得 HTML 源文件。
$lines = file(&#39;http://www.example.com/&#39;);
// 在数组中循环,显示 HTML 的源文件并加上行号。
foreach ($lines as $line_num => $line) {
  echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
// 另一个例子将 web 页面读入字符串。参见 file_get_contents()。
$html = implode(&#39;&#39;, file(&#39;http://www.example.com/&#39;));
// 从 PHP 5 开始可以使用可选标记参数
$trimmed = file(&#39;somefile.txt&#39;, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>

11、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_contents() 将返回 FALSE。  

参数:filename: 要读取的文件的名称。

use_include_path:As of PHP 5 the FILE_USE_INCLUDE_PATH can be used to trigger include path search.

context:A valid context resource created with stream_context_create(). 如果你不需要自定义 context,可以用 NULL 来忽略。


header("Content-Type:Text/html;charset=utf8");
// <= PHP 5
$file = file_get_contents(&#39;d:/test/test.txt&#39;, true);
echo $file.&#39;<br>&#39;;
// > PHP 5
$file = file_get_contents(&#39;d:/test/test.txt&#39;, FILE_USE_INCLUDE_PATH);
echo $file;
//结果
//this is test
//this is test

12、fgets();--从文件指针中读取一行


string fgets ( resource $handle [, int $length ] )
//从文件指针中读取一行。 

参数:handle:文件指针必须是有效的,必须指向由 fopen() 或 fsockopen() 成功打开的文件(并还未由 fclose() 关闭)。

length:从 handle 指向的文件中读取一行并返回长度最多为 length - 1 字节的字符串。碰到换行符(包括在返回值中)、EOF 或者已经读取了 length - 1 字节后停止(看先碰到那一种情况)。如果没有指定length,则默认为 1K,或者说 1024 字节。

13、ftell();-- 返回文件指针读/写的位置


int ftell ( resource $handle )
//返回由 handle 指定的文件指针的位置,也就是文件流中的偏移量。 

参数:handle : 文件指针必须是有效的,且必须指向一个通过 fopen() 或 popen() 成功打开的文件。在附加模式(加参数 "a" 打开文件)中 ftell() 会返回未定义错误。


header("Content-Type:Text/html;charset=utf8");
// opens a file and read some data
$fp = fopen("d:/test/test.txt", "r");
$data = fgets($fp, 4);
// where are we ?
echo ftell($fp); // 结果3
fclose($fp);

14、fseek();--在文件指针中定位


int fseek ( resource $handle , int $offset [, int $whence = SEEK_SET ] )
//在与 handle 关联的文件中设定文件指针位置。 新位置从文件头开始以字节数度量,是以 whence 指定的位置加上 offset。

参数 :handle:文件系统指针,是典型地由 fopen() 创建的 resource(资源)。

offset:偏移量。要移动到文件尾之前的位置,需要给 offset 传递一个负值,并设置 whence 为 SEEK_END。

whence values are:

1、SEEK_SET - 设定位置等于 offset 字节。

2、SEEK_CUR - 设定位置为当前位置加上 offset。

3、SEEK_END - 设定位置为文件尾加上 offset。


header("Content-Type:Text/html;charset=utf8");
$fp = fopen(&#39;d:\test\test.txt&#39;, &#39;r&#39;);
// read some data
$data = fgets($fp, 4096);
// move back to the beginning of the file
// same as rewind($fp);
 fseek($fp, 0);

15、flock();--轻便的咨询文件锁定 


bool flock ( resource $handle , int $operation [, int &$wouldblock ] )
//flock() 允许执行一个简单的可以在任何平台中使用的读取/写入模型(包括大部分的 Unix 派生版和甚至是 Windows)。  

参数:handle 文件系统指针,是典型地由 fopen() 创建的 resource(资源)。

operation 可以是以下值之一:

1、LOCK_SH取得共享锁定(读取的程序)。

2、LOCK_EX 取得独占锁定(写入的程序。

3、LOCK_UN 释放锁定(无论共享或独占)。

如果不希望 flock() 在锁定时堵塞,则是 LOCK_NB(Windows 上还不支持)。

wouldblock:如果锁定会堵塞的话(EWOULDBLOCK 错误码情况下),可选的第三个参数会被设置为 TRUE。(Windows 上不支持)


if (flock($fp, LOCK_EX)) { // 进行排它型锁定
  ftruncate($fp, 0);   // truncate file
  fwrite($fp, "Write something here\n");
  fflush($fp);      // flush output before releasing the lock
  flock($fp, LOCK_UN);  // 释放锁定
} else {
  echo "Couldn&#39;t get the lock!";
}

fclose($fp);

16、is_readable --判断给定文件名是否可读


bool is_readable ( string $filename )
//判断给定文件名是否存在并且可读。 

参数:filename:文件的路径。

返回值:如果由 filename 指定的文件或目录存在并且可读则返回 TRUE,否则返回 FALSE。 


$filename = &#39;d:\test\test.txt&#39;;
if (is_readable($filename)) {
  echo &#39;The file is readable&#39;;
} else {
  echo &#39;The file is not readable&#39;;
}
//The file is readable

17、is_writeable -- 判断给定的文件名是否可写


bool is_writable ( string $filename )
//如果文件存在并且可写则返回 TRUE。filename 参数可以是一个允许进行是否可写检查的目录名。  

参数:filename 要检查的文件名称。


$filename = &#39;d:\test\test.txt&#39;;
if (is_writeable($filename)) {
  echo &#39;The file is writeable&#39;;
} else {
  echo &#39;The file is not writeable&#39;;
}
//The file is writeable

18、chown(); -- 改变文件的所有者


bool chown ( string $filename , mixed $user )
//尝试将文件 filename 的所有者改成用户 user(由用户名或用户 ID 指定)。 只有超级用户可以改变文件的所有者。

参数:filename:文件路径。

user:用户名或数字。

二、目录函数

1、is_dir();--判断给定文件名是否是一个目录


bool is_dir ( string $filename )
//判断给定文件名是否是一个目录。 

参数:filename:如果文件名存在并且为目录则返回 TRUE。如果 filename 是一个相对路径,则按照当前工作目录检查其相对路径。


$filename = &#39;d:\test\test.txt&#39;;
var_dump(is_dir(&#39;$filename&#39;));  //bool(false) 
var_dump(is_dir(&#39;d:\test&#39;));    //bool(true)

2、mkdir();--新建目录


bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] )//尝试新建一个由 pathname 指定的目录。

参数:pathname:目录的路径。

mode:默认的 mode 是 0777,意味着最大可能的访问权。有关 mode 的更多信息请阅读 chmod() 页面。
mkdir("d:/test/test1", 0700);

3、opendir();--打开目录句柄


resource opendir ( string $path [, resource $context ] )
//打开一个目录句柄,可用于之后的 closedir(),readdir() 和 rewinddir() 调用中。 

参数:path 要打开的目录路径

context 参数的说明见手册中的 Streams API 一章。

4、readdir();--从目录句柄中读取条目


string readdir ([ resource $dir_handle ] )
//返回目录中下一个文件的文件名。文件名以在文件系统中的排序返回。 

参数:dir_handle 目录句柄的 resource,之前由 opendir() 打开


header("Content-Type:Text/html;charset=utf8");
if ($handle = opendir(&#39;d:/test&#39;)) {
  echo "Directory handle: $handle\n";
  echo "Files:\n";

  /* 这是正确地遍历目录方法 */
  while (false !== ($file = readdir($handle))) {
    echo "$file\n";
  }

  /* 这是错误地遍历目录的方法
  while ($file = readdir($handle)) {
    echo "$file\n";
  }
  */
  closedir($handle);
}

The above is the detailed content of Summary of PHP file functions and directory functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn