Home  >  Article  >  Backend Development  >  What are the PHP file operation functions? Summary of common file operation functions in PHP (with code)

What are the PHP file operation functions? Summary of common file operation functions in PHP (with code)

不言
不言Original
2018-07-24 15:56:533771browse

There are many kinds of PHP file operation functions. Today I will share with you the commonly used file operation functions in PHP. Without further ado, let’s take a look at what functions PHP file operations have.

1 php gets the file name:
basename — returns the file name part of the path

gives a file containing A string pointing to the full path of a file. This function returns the base file name. If the file name ends with suffix, this part will also be removed.

string basename ( string $path [, string $suffix ] )

$path = "/home/cate/index/index2.php";
$file = basename($path);
echo $file.&#39;<br>&#39;; //index2.php
$file2 = basename($path,&#39;.php&#39;);
echo $file2;    //index2
$file3 = basename($path,&#39;2.php&#39;);
echo $file2;    //index

2 php gets the directory name

dirname — Returns the directory portion of the path

string dirname ( string $path )

Gives a directory containing the full path to a file String, this function returns the directory name after removing the file name.

echo dirname(__FILE__);

__FILE__ points to the path where the current file is located, which is equivalent to getcwd();

3 php gets the path associative array

pathinfo — returns the file path information

pathinfo() Return An associative array contains path information. Includes the following array elements: dirname, basename and extension.

You can specify which units to return through the parameter options. They include: PATHINFO_DIRNAME, PATHINFO_BASENAME and PATHINFO_EXTENSION. The default is to return all units. If it is not required to obtain all units, this function returns a string.

<?php
$path_parts = pathinfo("/home/cate/index.action.html");
// /home/cate   文件目录
echo $path_parts["dirname"] . "<br/>";          
//  index.action.html  文件名
echo $path_parts["basename"] . "<br/>";         
//  html        扩展名
echo $path_parts["extension"] . "<br/>";
//直接获取扩展名       
echo pathinfo("/home/cate/index.action.html", PATHINFO_EXTENSION);

4 fopen function - open a file or URL

resource fopen ( string $filename , string $mode [ , bool $use_include_path [, resource $zcontext ]] )

Create and open for writing, change the file pointer Points to the file header. If the file already exists, the Create and open for reading and writing, change the file pointer Points to the file header. If the file already exists, the
<?php
    
$handle = fopen("doc.txt", "r");
    var_dump($handle);

D:\wamp\www\test\jsontest.php:3:resource(3stream)

<?php
    
$file = fopen(&#39;newtxt.txt&#39;,&#39;w&#39;)
or die
(&#39;无法打开文件&#39;);//不存在则自动创建
    $data = &#39;you are a coder!&#39;;
    fwrite($file,$data);
    $data = &#39;you are a MAN!&#39;;
    fwrite($file,$data);
    fclose($file);

5  fstat函数— 通过已打开的文件指针取得文件信息

array fstat ( resource $handle )

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

返回一个数组具有该文件的统计信息,该数组的格式详细说明于手册中 stat() 页面里。

<?php

// 打开文件
$fp = fopen("doc.txt", "r");

// 取得统计信息
$fstat = fstat($fp);

// 关闭文件
fclose($fp);
// 只显示关联数组部分
//print_r(array_slice($fstat, 13)); 

print_r($fstat);	//获取一个文件信息数组包括索引和关联数组

array_slice — 从数组中取出一段 返回数组

array array_slice ( array $array , int $offset [, int $length [, bool $preserve_keys ]] )

array_slice() 返回根据 offset 和 length 参数所指定的 array 数组中的一段序列。

如果 offset 非负,则序列将从 array 中的此偏移量开始。如果 offset 为负,则序列将从 array 中距离末端这么远的地方开始。

如果给出了 length 并且为正,则序列中将具有这么多的单元。如果给出了 length 并且为负,则序列将终止在距离数组末端这么远的地方。如果省略,则序列将从 offset 开始一直到 array 的末端。

<?php
$input = 
array("a", "b", "c", "d", "e");
$output = array_slice($input, 2);      // returns "c", "d", and "e"
$output = array_slice($input, -2, 1);  // returns "d"
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"
// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));

'r'

Open in read-only mode and point the file pointer to the file header.

'r '

Open in read and write mode, point the file pointer to the file header .

'w'

Open in writing mode and point the file pointer to the file header and truncate the file size to zero. If the file does not exist, try to create it.

'w '

Open in read and write mode, point the file pointer to the file header and truncate the file size to zero. If the file does not exist, try to create it.

'a'

##Open in writing mode and point the file pointer to the end of the file . If the file does not exist, try to create it.

'a '

Open in read and write mode, point the file pointer to the end of the file . If the file does not exist, try to create it.

##'x'

fopen()

call fails and returns FALSE, and generates an E_WARNING level error message. If the file does not exist, try to create it. This is equivalent to specifying the O_EXCL|O_CREAT flag to the underlying open(2) system call. This option is supported by PHP 4.3.2 and later, and can only be used for local files.

'x '

fopen()

call fails and returns FALSE, and generates an E_WARNING level error message. If the file does not exist, try to create it. This is equivalent to specifying the O_EXCL|O_CREAT flag to the underlying open(2) system call. This option is supported by PHP 4.3.2 and later, and can only be used for local files.

 

Array

 

(

 

[0] => c

 

[1] => d

 

)

 

Array

 

(

 

[2] => c

 

[3] => d

 

)

 

 

6 filesize函数— 取得文件大小

int filesize ( string $filename )

返回文件大小的字节数,如果出错返回 FALSE 并生成一条 E_WARNING 级的错误。

<?php
$filename = &#39;doc.txt&#39;;
echo $filename.&#39;:&#39;.filesize($filename).&#39;bytes&#39;;

doc.txt:46bytes

7.disk_free_space函数— 返回目录中的可用空间

float disk_free_space ( string $directory )

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

<?php
echo disk_free_space("C:").&#39;<br/>&#39;;
echo disk_free_space("D:").&#39;<br/>&#39;;
echo disk_free_space("/");

71001600000
186459181056

disk_total_space — 返回一个目录的磁盘总大小

8 fileatime函数— 取得文件的上次访问时间

filectime — 取得文件的 inode 修改时间

filemtime — 取得文件修改时间

9 file函数— 把整个文件读入一个数组中

<?php
$myfile = &#39;doc.txt&#39;;
$lines = file($myfile);
for($i=0,$len = count($lines);$i<$len;$i++){
    echo mb_convert_encoding($lines[$i], "UTF-8", "GBK").&#39;<br/>&#39;;
}

我是一个新手程序员,需要慢慢努力才能有所收获1! 
我是一个新手程序员,需要慢慢努力才能有所收获2! 
我是一个新手程序员,需要慢慢努力才能有所收获3! 
我是一个新手程序员,需要慢慢努力才能有所收获4! 
我是一个新手程序员,需要慢慢努力才能有所收获5! 
我是一个新手程序员,需要慢慢努力才能有所收获6!

mb_convert_encoding($lines[$i], "UTF-8", "GBK")

将每一行原来的WINDOWS下GBK格式的数据$lines[$i]转换为UTF-8格式

string mb_convert_encoding ( string $str , string $to_encoding [, mixed $from_encoding ] )

<?php
$myfile = &#39;doc.txt&#39;;
$encoding = mb_detect_encoding($myfile, 
array(&#39;GBK&#39;,&#39;UTF-16&#39;,&#39;UCS-2&#39;,&#39;UTF-8&#39;,&#39;BIG5&#39;,&#39;ASCII&#39;));
echo $encoding;

CP936 GBK

mb_detect_encoding — 侦测字符集  第一个为文件或者路径 第二个为可能的字符集

10 fgets函数— 从文件指针中读取一行

string fgets ( int $handle [, int $length ] )

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

出错时返回 FALSE

<?php
$handle = fopen(&#39;doc.txt&#39;,&#39;r&#39;);
if ($handle){
    while (!feof($handle)){
        $data[] = fgets($handle,1024);
    }
    print_r($data);
    fclose($handle);
}
Array
(
    [0] => 我是一个新手程序员,需要慢慢努力才能有所收获1!
    [1] => 我是一个新手程序员,需要慢慢努力才能有所收获2!
    [2] => 我是一个新手程序员,需要慢慢努力才能有所收获3!
    [3] => 我是一个新手程序员,需要慢慢努力才能有所收获4!
    [4] => 我是一个新手程序员,需要慢慢努力才能有所收获5!
    [5] => 我是一个新手程序员,需要慢慢努力才能有所收获6!
)

feof — 测试文件指针是否到了文件结束的位置

如果服务器没有关闭由 fsockopen() 所打开的连接,feof() 会一直等待直到超时而返回 TRUE。默认的超时限制是 60 秒,可以使用 stream_set_timeout() 来改变这个值。

fclose — 关闭一个已打开的文件指针

11 fgetss函数—— 从文件指针中读取一行并过滤掉 HTML 标记
fgets() 相同,只除了 fgetss 尝试从读取的文本中去掉任何 HTML 和 PHP 标记。

   可以用可选的第三个参数指定哪些标记不被去掉

file_exists — 检查文件或目录是否存在

bool file_exists ( string $filename )

如果由 filename 指定的文件或目录存在则返回 TRUE,否则返回 FALSE

12 file_put_contents函数— 将一个字符串写入文件

int file_put_contents ( string $filename , string $data [, int $flags [, resource $context ]] )

和依次调用 fopen()fwrite() 以及 fclose() 功能一样。

filename 要写入数据的文件名
data  要写入的数据。类型可以是 stringarray(但不能为多维数组),或者是 stream 资源
flags  可选,规定如何打开/写入文件。可能的值:
FILE_USE_INCLUDE_PATH:检查 filename 副本的内置路径
FILE_APPEND:在文件末尾以追加的方式写入数据
LOCK_EX:对文件上锁
context  可选,Context是一组选项,可以通过它修改文本属性

  • fopen() - 打开文件或者 URL

  • fwrite() - 写入文件(可安全用于二进制文件)

  • file_get_contents() - 将整个文件读入一个字符串

<?php
echo file_put_contents(&#39;doc.txt&#39;,&#39;你是一个程序员7&#39;,FILE_APPEND
);

返回字节数22

如果文件不存在,则创建文件,相当于fopen()函数行为。

如果文件存在,默认将清空文件内的内容,可设置 flags 参数值为 FILE_APPEND 以避免。

file_put_contents 函数可安全用于二进制对象。

如果对于确定已经存在的文件,最好进行一个判断

if 
(file_exists(&#39;test.txt&#39;)) {
    file_put_contents(&#39;test.txt&#39;,&#39;contents&#39; );
}

相关推荐:

php文件操作的方法及实例详解

The above is the detailed content of What are the PHP file operation functions? Summary of common file operation functions in PHP (with code). 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