Summary of commonly used file operation functions in PHP
Apr 03, 2024 pm 02:52 PM目录
- 1 :basename()
- 2 :copy()
- 3 :dirname()
- 4 :disk_free_space()
- 5 :disk_total_space()
- 6 :file_exists()
- 7 :file_get_contents()
- 8 :file_put_contents()
- 9 :filesize()
- 10 :filetype()
- 11 :glob()
- 12 :is_dir()
- 13 :is_writable()
- 14 :mkdir()
- 15 :move_uploaded_file()
- 16 :parse_ini_file()
- 17 :realpath()
- 18 :rename()
- 19 :tempnam()
- 20 :tmpfile()
- 21:unlink()
- 22 :chmod()
- 23:chown()
- 24:chgrp()
php小编柚子精心整理了Summary of commonly used file operation functions in PHP,为广大PHP开发者提供了一份实用的文件操作函数参考指南。通过本文的总结,读者可以快速了解PHP中文件操作的各种常用函数,提高文件处理的效率和准确性。无论是对于初学者还是有一定开发经验的开发者,都能从文章中获得实用的技术知识和经验。
注:文件操作函数的行为受到 php.ini 中设置的影响。
当在 Unix 平台上规定路径时,正斜杠 (/) 用作目录分隔符。而在 windows 平台上,正斜杠 (/) 和反斜杠 () 均可使用。
1 :basename()
返回路径中的文件名。分为带扩展名和不带扩展名的。
语法:basename(path,suffix)
Path:必需。规定要检查的路径。
Suffix:可选。规定文件扩展名。如果文件有名有文件扩展名,将不会显示这个扩展名。
// basename $path = "/testWEB/home.php"; // 输出文件名,包含扩展名 echo basename($path) ."<br/>";// home.php // 输出文件名,不包含扩展名 echo basename($path,".php");// home
2 :copy()
复制文件。该函数如果成功则返回 TRUE,如果失败则返回 FALSE。如果目标文件已存在,将会被覆盖。
语法:copy(file,to_file)
File:必需。规定要复制的文件。
to_file:必需。规定复制文件的目的地。
// 复制文件,返回值为bool echo copy("source.txt","target.txt");
3 :dirname()
返回路径中的目录部分。
语法:dirname(path)
Path:必需。规定要检查的路径。
// 返回文件路径 echo dirname("c:/testweb/home.php")."<br>";// c:/testweb/ echo dirname("/testweb/home.php");// /testweb/
4 :disk_free_space()
返回目录的可用空间。,以字节为单位。
语法:disk_free_space(directory)
Directory:必需。规定要检查的目录。(该目录有限制)
// 返回指定目录的可用空间(查询的目录是有限制的) echo disk_free_space("D:/wwwroot/xxx.com/");
5 :disk_total_space()
返回一个目录的磁盘总容量。返回字节数
语法:disk_total_space(directory)
Directory:必需。规定要检查的目录。
echo disk_total_space("C:/Windows/Temp/"); echo "<hr>";
6 :file_exists()
检查文件或目录是否存在。返回bool值
语法:file_exists(path)
Path:必需。规定要检查的路径。
// 查看test.txt是否存在,返回bool值 echo file_exists("target.txt"); // 1 echo "<hr>";
7 :file_get_contents()
将文件读入字符串。
语法:file_get_contents(path,include_path,context,start,max_length)
Path:必需。规定要读取的文件。
include_path:可选。如果您还想在 include_path(在 php.ini 中)中搜索文件的话,请设置该参数为 '1'。
Context:可选。规定文件句柄的环境。context 是一套可以修改流的行为的选项。若使用 NULL,则忽略。
Start:可选。规定在文件中开始读取的位置。该参数是 PHP 5.1 中新增的。
max_length:可选。规定读取的字节数。该参数是 PHP 5.1 中新增的。
// 读取文件 echo file_get_contents("target.txt"); echo "<hr>";
提示: 该函数是二进制安全的。(意思是二进制数据(如图像)和字符数据都可以使用此函数写入。)
8 :file_put_contents()
将字符串写入文件。如果成功,该函数将返回写入文件中的字符数。如果失败,则返回 False。
语法:int file_put_contents ( string filename,mixedfilename , mixed filename,mixeddata [, int flags=0[,resourceflags = 0 [, resource flags=0[,resourcecontext ]] )
File:必需。规定要写入数据的文件。如果文件不存在,则创建一个新文件。
Data:必需。规定要写入文件的数据。可以是字符串、数组或数据流。
Mode:可选。规定如何打开/写入文件。可能的值:FILE_USE_INCLUDE_PATH/FILE_APPEND/LOCK_EX
Context:可选。规定文件句柄的环境。context 是一套可以修改流的行为的选项。
// 写入文件 echo file_put_contents("sites.txt","Runoob"); echo "<hr>";
9 :filesize()
函数返回指定文件的大小。
如果成功,该函数返回文件大小的字节数。如果失败,则返回 FALSE。
语法:filesize(filename)
Filename:必需。规定要检查的文件。
// 返回文件大小 echo filesize("target.txt"); echo "<hr>";
10 :filetype()
函数返回指定文件或目录的类型。
若成功,则返回 7 种可能的值。若失败,则返回 false。
语法:filetype(filename)
Filename:必需。规定要检查的文件。
// 返回文件类型 echo filetype("target.txt"); echo "<hr>";
11 :glob()
返回一个包含匹配指定模式的文件名/目录的数组。
glob() 函数返回匹配指定模式的文件名或目录。
该函数返回一个包含有匹配文件 / 目录的数组。如果出错返回 false。
语法:glob(pattern,flags)
File:必需。规定检索模式。
Size:可选。规定特殊的设定。
- GLOB_MARK - 在每个返回的项目中加一个斜线
- GLOB_NOSORT - 按照文件在目录中出现的原始顺序返回(不排序)
- GLOB_NOCHECK - 如果没有文件匹配则返回用于搜索的模式
- GLOB_NOESCAPE - 反斜线不转义元字符
- GLOB_BRACE - 扩充 {a,b,c} 来匹配 'a','b' 或 'c'
- GLOB_ONLYDIR - 仅返回与模式匹配的目录项
- GLOB_ERR - 停止并读取错误信息(比如说不可读的目录),默认的情况下忽略所有错误
注释:GLOB_ERR 是 PHP 5.1 添加的。
echo "<pre class="brush:php;toolbar:false">"; var_dump(glob("*.*")); echo "<hr>";
12 :is_dir()
判断指定的文件名是否是一个目录。
语法:is_dir(file)
File:必需。规定要检查的文件。
$file = "D:/wwwroot/xxx.com/"; if(is_dir($file)) { echo ("$file is a directory"); } else { echo ("$file is not a directory"); } echo "<hr>";
13 :is_writable()
判断文件是否可写。如果文件存在并且可写则返回 true。
语法:is_writable(file)
File:必需。规定要检查的文件。
$file = "target.txt"; if(is_writable($file)) { echo ("$file is writeable"); } else { echo ("$file is not writeable"); } echo "<hr>";
14 :mkdir()
创建目录,如果成功该函数返回 TRUE,如果失败则返回 FALSE。
语法:mkdir(path,mode,recursive,context)
Path:必需。规定要创建的目录的名称。
Mode:可选。规定权限。默认是 0777(允许全局访问)。
mode 参数由四个数字组成:
第一个数字通常是 0
第二个数字规定所有者的权限
第三个数字规定所有者所属的用户组的权限
第四个数字规定其他所有人的权限
可能的值(如需设置多个权限,请对下面的数字进行总计):
1 = 执行权限
2 = 写权限
4 = 读权限
Recursive:可选。规定是否设置递归模式。(PHP 5 中新增的)
Context:可选。规定文件句柄的环境。context 是一套可以修改流的行为的选项。(PHP 5 中新增的)
echo mkdir("testing"); echo "<hr>";
注释: mode 参数在 Windows 平台上被忽略。
15 :move_uploaded_file()
将上传的文件移动到新位置。若成功,则返回 true,否则返回 false。
文件上传的核心就是这个文件
语法:move_uploaded_file(file,newloc)
File:必需。规定要移动的文件。
Newloc:必需。规定文件的新位置。
注释:本函数仅用于通过 Http POST 上传的文件。
注意:如果目标文件已经存在,将会被覆盖。
16 :parse_ini_file()
函数解析一个配置文件(ini 文件),并以数组的形式返回其中的设置。
语法:parse_ini_file(file,process_sect<strong class="keylink">io</strong>ns)
File:必需。规定要检查的 ini 文件。
process_sections:可选。如果设置为 TRUE,则返回一个多维数组,包括了配置文件中每一节的名称和设置。默认是 FALSE。
echo "<pre class="brush:php;toolbar:false">"; var_dump(parse_ini_file("test.ini")); echo "<hr>";
注:此ini文件不一定非的是php.ini,也可以是你自己的ini配置文件。
17 :realpath()
该函数删除所有符号连接(比如 '/./', '/../' 以及多余的 '/'),并返回绝对路径名。
如果失败,该函数返回 FALSE。
语法:realpath(path)
Path:必需。规定要检查的路径。
echo realpath("test.ini");
18 :rename()
rename() 函数重命名文件或目录。
如果成功,该函数返回 TRUE。如果失败,则返回 FALSE。
语法:rename(oldname,newname,context)
Oldname:必需。规定要重命名的文件或目录。
Newname:必需。规定文件或目录的新名称。
Context:可选。规定文件句柄的环境。context 是一套可以修改流的行为的选项。
echo rename("test.ini","testss.ini"); echo "<hr>";
19 :tempnam()
创建唯一的临时文件。若成功,则该函数返回新的临时文件名。若失败,则返回 false。
语法:tempnam(dir,prefix)
Dir:必需。规定创建临时文件的目录。
Prefix:必需。规定文件名的开头。
echo tempnam("D:wwwrootxxx.com","TMP0"); echo "<hr>";
注: 此方法创建的文件,如果不再需要该文件则要删除此文件,不会自动删除的。
20 :tmpfile()
建立临时文件。此函数创建的临时文件会在文件关闭后(用 fclose())或当脚本结束后自动被删除。
语法:tmpfile()
$temp = tmpfile(); fwrite($temp, "Testing, testing."); // 将文件指针的位置倒回文件的开头。 rewind($temp); // 从文件中读取1K数据 echo fread($temp,1024); //This removes the file fclose($temp);
21:unlink()
删除文件。如果成功,该函数返回 TRUE。如果失败,则返回 FALSE。
语法:unlink(filename,context)
Filename:必需。规定要删除的文件。
Context:可选。规定文件句柄的环境。context 是一套可以修改流的行为的选项。
// 如果没有text.txt文件,这样写输出的结果会报警告,测试代码,就这样了 // 实际用的时候,需要注意这个问题 $file = "test.txt"; if (!unlink($file)) { echo ("Error deleting $file"); } else { echo ("Deleted $file"); }
22 :chmod()
改变文件权限。如果成功则返回 TRUE,如果失败则返回 FALSE。
语法:chmod(file,mode)
File:必需。规定要检查的文件。
Mode:必需。规定新的权限。
mode 参数由 4 个数字组成:
第一个数字通常是 0
第二个数字规定所有者的权限
第三个数字规定所有者所属的用户组的权限
第四个数字规定其他所有人的权限
可能的值(如需设置多个权限,请对下面的数字进行总计):
1 = 执行权限
2 = 写权限
4 = 读权限
echo chmod("target.txt",0600); echo "<hr>";
23:chown()
改变文件所有者。如果成功则返回 TRUE,如果失败则返回 FALSE。
语法:chown(file,owner)
File:必需。规定要检查的文件。
Owner:必需。规定新的所有者。可以是用户名或用户的 ID。
echo chown("target.txt","root"); echo "<hr>";
24:chgrp()
改变文件组。如果成功则返回 TRUE,否则返回 FALSE。
语法:chgrp(file,group)
File:必需。规定要检查的文件。
Group:可选。规定新的组。可以是组名或组的 ID。
echo chgrp("test.txt","admin"); echo "<hr>";
The above is the detailed content of Summary of commonly used file operation functions in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This article will explain in detail how PHP formats rows into CSV and writes file pointers. I think it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. Format rows to CSV and write to file pointer Step 1: Open file pointer $file=fopen("path/to/file.csv","w"); Step 2: Convert rows to CSV string using fputcsv( ) function converts rows to CSV strings. The function accepts the following parameters: $file: file pointer $fields: CSV fields as an array $delimiter: field delimiter (optional) $enclosure: field quotes (

This article will explain in detail about changing the current umask in PHP. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. Overview of PHP changing current umask umask is a php function used to set the default file permissions for newly created files and directories. It accepts one argument, which is an octal number representing the permission to block. For example, to prevent write permission on newly created files, you would use 002. Methods of changing umask There are two ways to change the current umask in PHP: Using the umask() function: The umask() function directly changes the current umask. Its syntax is: intumas

This article will explain in detail how to create a file with a unique file name in PHP. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. Creating files with unique file names in PHP Introduction Creating files with unique file names in PHP is essential for organizing and managing your file system. Unique file names ensure that existing files are not overwritten and make it easier to find and retrieve specific files. This guide will cover several ways to generate unique filenames in PHP. Method 1: Use the uniqid() function The uniqid() function generates a unique string based on the current time and microseconds. This string can be used as the basis for the file name.

This article will explain in detail about PHP calculating the MD5 hash of files. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP calculates the MD5 hash of a file MD5 (MessageDigest5) is a one-way encryption algorithm that converts messages of arbitrary length into a fixed-length 128-bit hash value. It is widely used to ensure file integrity, verify data authenticity and create digital signatures. Calculating the MD5 hash of a file in PHP PHP provides multiple methods to calculate the MD5 hash of a file: Use the md5_file() function. The md5_file() function directly calculates the MD5 hash value of the file and returns a 32-character

This article will explain in detail how PHP truncates files to a given length. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. Introduction to PHP file truncation The file_put_contents() function in PHP can be used to truncate files to a specified length. Truncation means removing part of the end of a file, thereby shortening the file length. Syntax file_put_contents($filename,$data,SEEK_SET,$offset);$filename: the file path to be truncated. $data: Empty string to be written to the file. SEEK_SET: designated as the beginning of the file

This article will explain in detail the numerical encoding of the error message returned by PHP in the previous Mysql operation. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. . Using PHP to return MySQL error information Numeric Encoding Introduction When processing mysql queries, you may encounter errors. In order to handle these errors effectively, it is crucial to understand the numerical encoding of error messages. This article will guide you to use php to obtain the numerical encoding of Mysql error messages. Method of obtaining the numerical encoding of error information 1. mysqli_errno() The mysqli_errno() function returns the most recent error number of the current MySQL connection. The syntax is as follows: $erro

This article will explain in detail how PHP returns an array after key value flipping. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP Key Value Flip Array Key value flip is an operation on an array that swaps the keys and values in the array to generate a new array with the original key as the value and the original value as the key. Implementation method In PHP, you can perform key-value flipping of an array through the following methods: array_flip() function: The array_flip() function is specially used for key-value flipping operations. It receives an array as argument and returns a new array with the keys and values swapped. $original_array=[

This article will explain in detail how PHP determines whether a specified key exists in an array. The editor thinks it is very practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP determines whether a specified key exists in an array: In PHP, there are many ways to determine whether a specified key exists in an array: 1. Use the isset() function: isset($array["key"]) This function returns a Boolean value, true if the specified key exists, false otherwise. 2. Use array_key_exists() function: array_key_exists("key",$arr
