Home php教程 php手册 【推荐】有趣儿的PHP文件操作常用函数总结

【推荐】有趣儿的PHP文件操作常用函数总结

Jun 06, 2016 pm 07:48 PM
php function Commonly used Summarize recommend operate document

有趣儿的PHP文件操作常用函数总结 以下是个人总结的PHP文件操作函数。当然,这只是部分,还有很多,我没有列出来。 一 、解析路径: 1 获得文件名: basename(); 给出一个包含有指向一个文件的全路径的字符串,本函数返回基本的文件名。如果文件名是以 suffix

有趣儿的PHP文件操作常用函数总结

以下是个人总结的PHP文件操作函数。当然,这只是部分,还有很多,我没有列出来。


 

一 、解析路径:

1 获得文件名:
basename();
给出一个包含有指向一个文件的全路径的字符串,本函数返回基本的文件名。如果文件名是以 suffix 结束的,那这一部分也会被去掉。
eg:

$path = "/home/httpd/html/index.php";
$file = basename($path,".php"); // $file is set to "index"

 

 

2 得到目录部分:
dirname();
给出一个包含有指向一个文件的全路径的字符串,本函数返回去掉文件名后的目录名。
eg:

$path = "/etc/passwd";
$file = dirname($path); // $file is set to "/etc"

 

 

3 得到路径关联数组
pathinfo();
得到一个指定路径中的三个部分:目录名,基本名,扩展名。
eg:

$pathinfo = pathinfo("www/test/index.html");
var_dump($pathinfo);
// $path['dirname']
$path['basename']
$path['extenssion']

 

 


二、文件类型
1. filetype();
返回文件的类型。可能的值有 fifo,char,dir,block,link,file 和 unknown。
eg:

echo filetype('/etc/passwd'); // file
echo filetype('/etc/');        // dir

 

 


三、得到给定文件有用信息数组(很有用)

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

 

// 打开文件
$fp = fopen("/etc/passwd", "r");
// 取得统计信息
$fstat = fstat($fp);
// 关闭文件
fclose($fp);
// 只显示关联数组部分
print_r(array_slice($fstat, 13));

 

 

2. stat()
获取由 filename 指定的文件的统计信息(类比fstat())

 

四、计算大小
1. filesize()
返回文件大小的字节数,如果出错返回 FALSE 并生成一条 E_WARNING 级的错误。
eg:

// 输出类似:somefile.txt: 1024 bytes
$filename = 'somefile.txt';
echo $filename . '' . filesize($filename. ' bytes';

 


2. disk_free_space()
获得目录所在磁盘分区的可用空间(字节单位)
eg

// $df 包含根目录下可用的字节数
$df = disk_free_space("/");
//在 Windows 下:
disk_free_space("C:");
disk_free_space("D:");

 


3. disk_total_space()
返回一个目录的磁盘总大小
eg:(同上,换掉函数)

另:如需要计算一个目录大小,可以编写一个递归函数来实现

【推荐】有趣儿的PHP文件操作常用函数总结【推荐】有趣儿的PHP文件操作常用函数总结代码

function dir_size($dir){
$dir_size = 0;
if($dh = @opendir($dir)){
while(($filename = readdir($dh)) != false){
if($filename !='.' and $filename !='..'){

     
if(is_file($dir.'/'.$filename)){
$dir_size +=filesize($dir.'/'.$filename);

}
else if(is_dir($dir.'/'.$filename)){

      
$dir_size +=dir_size($dir.'/'.$filename);
}
}

                   }
#end while

            }
# end opendir

@
closedir($dh);
return $dir_size;
#end function

 

 

五、 访问与修改时间
1. fileatime(): 最后访问时间
2. filectime(): 最后改变时间(任何数据的修改)
3. filemtime(): 最后修改时间(指仅是内容修改)

 

六、 文件的I/O操作

1. fopen -- 打开文件或者 URL

mode 说明
'r' 只读方式打开,将文件指针指向文件头。
'r+' 读写方式打开,将文件指针指向文件头。
'w' 写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。
'w+' 读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。
'a' 写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。
'a+' 读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。
'x' 创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,
'x+' 创建并以读写方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE
eg:

$handle = fopen("/home/rasmus/file.txt", "r");

 

 

2. file -- 把整个文件读入一个数组中(此函数是很有用的)
和 file_get_contents() 一样,只除了 file() 将文件作为一个数组返回。数组中的每个单元都是文件中相应的一行,包括换行符在内。如果失败 file() 返回 FALSE。
eg:

【推荐】有趣儿的PHP文件操作常用函数总结【推荐】有趣儿的PHP文件操作常用函数总结代码

$lines = file('http://www.example.com/');
// 在数组中循环,显示 HTML 的源文件并加上行号。
foreach ($lines as $line_num => $line) {
echo "Line #{$line_num} : " . htmlspecialchars($line. "
\n
";
}
// 另一个例子将 web 页面读入字符串。参见 file_get_contents()。
$html = implode('', file ('http://www.example.com/'));

 

 

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

$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}

 

 

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

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


   另:对的目录的操作:
1. opendir -- 打开目录句柄,打开一个目录句柄,可用于之后的 closedir(),readdir() 和 rewinddir() 调用中。
2. readdir -- 从目录句柄中读取条目,返回目录中下一个文件的文件名。文件名以在文件系统中的排序返回。
eg:


 

 

【推荐】有趣儿的PHP文件操作常用函数总结【推荐】有趣儿的PHP文件操作常用函数总结代码

// 注意在 4.0.0-RC2 之前不存在 !== 运算符

if ($handle = opendir('/path/to/files')) {
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);
}

 


3. scandir -- 列出指定路径中的文件和目录(很有用),返回一个 array,包含有 directory 中的文件和目录。
默认的排序顺序是按字母升序排列。如果使用了可选参数 sorting_order(设为 1),则排序顺序是按字母降序排列。
eg:

$dir    = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);

print_r($files1);
print_r($files2);   

 


 

另外注:

七、 对文件属性的操作 (操作系统环境不同,可能有所不一样,这点要注意)

    1 文件是否可读

       bool is_readable ( string filename )

         如果由 filename 指定的文件或目录存在并且可读则返回 TRUE

        记住 PHP 也许只能以运行 webserver 的用户名(通常为 'nobody')来访问文件。不计入安全模式的限制。

    文件是否可写

         bool is_writable ( string filename )

        如果文件存在并且可写则返回 TRUEfilename 参数可以是一个允许进行是否可写检查的目录名。

         记住 PHP 也许只能以运行 webserver 的用户名(通常为 'nobody')来访问文件。不计入安全模式的限制

    检查文件是否存在(这个函数很有趣

    bool file_exists ( string filename )

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

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles