Table of Contents
php文件,文件夹(目录)操作函数总结
您可能感兴趣的文章
Home php教程 php手册 php文件,文件夹(目录)操作函数总结

php文件,文件夹(目录)操作函数总结

Jun 13, 2016 am 09:05 AM
php operate document folder Table of contents

php文件,文件夹(目录)操作函数总结

本文章来给各位同学总结一下在php中一些常用的文件夹/文件目录操作函数总结,这些只是简单的介绍一些基础方法做个备注。

1、创建目录(mkdir)

bool mkdir (string $pathname [,int $mode [,bool $recursive [,resource $context ]]] )

<?php  
mkdir("/path/to/my/dir", 0777);  //成功返回true,失败返回false;
Copy after login

2、判断文件是否存在(file_exist)

bool file_exists (string $filename )

<?php  
$filename = '/path/to/phpernote.txt';
echo file_exists($filename)?'文件存在':'文件不存在';
Copy after login

3、检查指定的文件是否是目录,一般也用于判断目录是否存在(is_dir)

bool is_dir (string $filename )

<?php
var_dump(is_dir('a_file.txt'));//  输出false  
var_dump(is_dir('wwwroot/phpernote')); //相对当前目录检查wwwroot/phpernote目录是否存在,存在输出true,不存在输出false
var_dump(is_dir('..')); //输出true
Copy after login

注释:本函数的结果会被缓存。请使用 clearstatcache() 来清除缓存。

4、判断给定文件名是否为一个正常的文件 (is_file)

bool is_file ( string $filename )

<?php  
var_dump(is_file('a_file.txt'));//true  
var_dump(is_file('/usr/bin/'));//false
Copy after login

5、锁定或释放文件(flock)

bool flock ( string $filename, string $lock [,mix $block] )

lock 参数可以是以下值之一:

要取得共享锁定(读取的程序),将 lock 设为 LOCK_SH(PHP 4.0.1 以前的版本设置为 1)。
要取得独占锁定(写入的程序),将 lock 设为 LOCK_EX(PHP 4.0.1 以前的版本中设置为 2)。
要释放锁定(无论共享或独占),将 lock 设为 LOCK_UN(PHP 4.0.1 以前的版本中设置为 3)。
如果不希望 flock() 在锁定时堵塞,则给 lock 加上 LOCK_NB(PHP 4.0.1 以前的版本中设置为 4)。

block 可选。若设置为 1 或 true,则当进行锁定时阻挡其他进程。

提示:可以通过 fclose() 来释放锁定操作,代码执行完毕时也会自动调用。例如:

<?php
$file = fopen("test.txt","w+");
// 排它性的锁定
if (flock($file,LOCK_EX)){
  if(is_writable($file))
  fwrite($file,"www.phpernote.com 总结的文章");
  // 解锁
  flock($file,LOCK_UN);
}else{
  echo "锁定文件失败!";
}
fclose($file);
Copy after login

6、判断给定文件名是否为一个符号连接 (is_link)

bool is_link ( string $filename )

<?php  
var_dump(is_link("a.lnk")); //输出true
Copy after login

注释:本函数的结果会被缓存。请使用 clearstatcache() 来清除缓存。

7、删除目录 (rmdir)此函数仅删除空目录(rmdir)

bool rmdir ( string $dirname ) 

<?php
var_dump(rmdir("/usr/local/a")); //当a为空目录删除成功,a为非空目录删除失败
Copy after login

8、删除文件(unlink)

bool unlink ( string $filename )

<?php
while(is_file($wwwphpernotecom) == TRUE){
	chmod($wwwphpernotecom, 0666);//设置可读取,可写入权限
	unlink($wwwphpernotecom);
}
Copy after login

9、获取文件或目录的权限(fileperms)

mix fileperms ( filename )

<?php
//若成功,则返回文件的访问权限。若失败,则返回 false
echo fileperms("test.txt");//输出:33206
Copy after login

以八进制值返回权限

<?php
echo substr(sprintf("%o",fileperms("test.txt")),-4);//输出:1777
Copy after login

提示:本函数的结果会被缓存。请使用 clearstatcache() 来清除缓存。

10、获取指定文件或目录的类型(filetype)

mix filetype ( filename )

若成功,则返回 7 种可能的值(fifo char dir block link file unknown)。若失败,则返回 false。例如:

<?php
echo filetype("test.txt");//输出:file
Copy after login

提示:本函数的结果会被缓存。请使用 clearstatcache() 来清除缓存。

11、读取目录文件(opendir readir closedir)

resource opendir ( string $path [,resource $context ] )

打开一个目录句柄,可用于之后的 closedir(),readdir() 和 rewinddir() 调用中。

string readdir ( resource $dir_handle )

返回目录中下一个文件的文件名。文件名以在文件系统中的排序返回。

void closedir ( resource $dir_handle )

关闭由 dir_handle 指定的目录流。流必须之前被 opendir() 所打开。

void rewinddir ( resource $dir_handle )
 
将 dir_handle 指定的目录流重置到目录的开头。

下面是一个完整的读取目录文件的示例:

<?php
$dir = "/etc/php5/";
if (is_dir($dir)) {  
    if ($dh = opendir($dir)) {  
        while (($file = readdir($dh)) !== false) {  
            echo "文件名: $file : 文件类型: " . filetype($dir . $file) . "\n";  
        }  
        closedir($dh);  
    }  
}
Copy after login

12、重命名文件或目录(rename)

bool rename ( oldname, newname, context )

<?php
//将当前目录下的子目录a下面的文件1.gif重命名为2.gif
rename('/a/1.gif', '/a/2.gif');
Copy after login

说明:对目录也一样。系统会返回操作结果,成功则返回 TRUE,失败则返回 FALSE。

如果要移动文件或目录,只要将重命名后的路径设置为新的路径就可以了,例如:

<?php
//将当前目录下的子目录a下面的文件1.gif,移动到当前目录下的子目录b,并且重命名为2.gif
rename('/a/1.gif', '/b/2.gif');
//注意:如果目录b不存在,就会移动失败
Copy after login

13、复制(拷贝)文件(copy)

bool copy ( source, destination )

<?php
//将当前目录下的子目录a下面的文件1.gif,复制到当前目录下的子目录b,并命名为2.gif
copy('/a/1.gif', '/b/1.gif');
Copy after login

说明:不能对目录进行此项操作;如果目标文件(上面的/b/1.gif)已经存在,原来的文件将被覆盖;如果要移动文件的话,请使用 rename() 函数。

14、获取目录的可用空间(disk_free_space)

disk_free_space ( directory )

<?php
echo disk_free_space("C:");//输出:209693288558
Copy after login

15、判断指定的文件是否可写(is_writable 或 is_writeable)

bool is_writable ( file )

说明:如果文件存在并且可写则返回 true;file 参数可以是一个允许进行是否可写检查的目录名;本函数的结果会被缓存。请使用 clearstatcache() 来清除缓存。例如:

<?php
$file = "test.txt";
//或者:$file = 'd:\wwwroot\phpernote\';
echo is_writable($file)?'可写':'不可写';
Copy after login

16、以读写(w+)模式建立一个具有唯一文件名的临时文件(tmpfile)

resource tmpfile()

<?php
$temp = tmpfile();
fwrite($temp, "Testing, www.phpernote.com");
//倒回文件的开头
rewind($temp);
//从文件中读取 1k
echo fread($temp,1024);
//删除文件
fclose($temp);
//文件会在关闭后(用 fclose())自动被删除,或当脚本结束后
//输出:Testing, www.phpernote.com
Copy after login

17、改变文件权限模式(chmod)

bool chmod ( file [,mode] )

mode 可选。规定新的权限。该参数由 4 个数字组成:
第一个数字永远是 0
第二个数字规定所有者的权限
第二个数字规定所有者所属的用户组的权限
第四个数字规定其他所有人的权限
可能的值(如需设置多个权限,请对下面的数字进行总计):
1 - 执行权限
2 - 写权限
4 - 读权限

<?php
// 所有者可读写,其他人没有任何权限
chmod("test.txt",0600);
// 所有者可读写,其他人可读
chmod("test.txt",0644);
// 所有者有所有权限,其他所有人可读和执行
chmod("test.txt",0755);
// 所有者有所有权限,所有者所在的组可读
chmod("test.txt",0740);
Copy after login

18、扩展函数,方法

php读取目录并列表显示目录中的文件的函数

PHP删除目录及目录下所有文件

更多文件,文件夹(目录)函数请参考:

PHP Filesystem 函数

您可能感兴趣的文章

  • php清空(删除)指定目录下的文件,不删除目录文件夹的方法
  • php判断文件或目录(文件夹)是否存在
  • linux chmod(文件或文件夹权限设定)命令参数及用法详解
  • MySQL通过命令形式导入与导出.sql文件备份数据操作的实例
  • php提取身份证号码中的生日日期以及验证是否为未成年人的函数
  • PHP向文件写入或追加数据
  • linux删除文件,文件夹命令rm 命令详解
  • Linux命令文件目录管理cat命令
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 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

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,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

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.

See all articles