Table of Contents
Summary of PHP file and folder (directory) operation functions
您可能感兴趣的文章
Home Backend Development PHP Tutorial PHP file, folder (directory) operation function summary_PHP tutorial

PHP file, folder (directory) operation function summary_PHP tutorial

Jul 13, 2016 am 09:55 AM
php operate document folder Table of contents

Summary of PHP file and folder (directory) operation functions

This article will give you a summary of some commonly used folder/file directory operation functions in PHP. These Just a brief introduction to some basic methods as a note.

1. Create directory (mkdir)

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

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

2. Determine whether the file exists (file_exist)

bool file_exists (string $filename )

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

3. Check whether the specified file is a directory, which is generally used to determine whether the directory exists (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

Note: The result of this function will be cached. Please use clearstatcache() to clear the cache.

4. Determine whether the given file name is a normal file (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. Lock or release files (flock)

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

The lock parameter can be one of the following values:

To obtain a shared lock (reading program), set lock to LOCK_SH (set to 1 in versions prior to PHP 4.0.1).
To obtain an exclusive lock (writing program), set lock to LOCK_EX (set to 2 in versions prior to PHP 4.0.1).
To release a lock (whether shared or exclusive), set lock to LOCK_UN (set to 3 in versions prior to PHP 4.0.1).
If you do not want flock() to block on lock, add LOCK_NB to lock (set to 4 in versions prior to PHP 4.0.1).

block optional. If set to 1 or true, blocks other processes while locking.

Tip: You can use fclose() to release the lock operation, which will be automatically called when the code is executed. For example:

<?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. Determine whether the given file name is a symbolic link (is_link)

bool is_link ( string $filename )

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

Note: The result of this function will be cached. Please use clearstatcache() to clear the cache.

7. Delete directory (rmdir) This function only deletes empty directories (rmdir)

bool rmdir ( string $dirname )

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

8. Delete files (unlink)

bool unlink ( string $filename )

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

9. Obtain permissions for files or directories (fileperms)

mix fileperms ( filename )

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

Return permissions as octal value

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

Tip: The result of this function will be cached. Please use clearstatcache() to clear the cache.

10. Get the type of the specified file or directory (filetype)

mix filetype ( filename )

If successful, return 7 possible values ​​(fifo char dir block link file unknown). On failure, returns false. For example:

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

Tip: The result of this function will be cached. Please use clearstatcache() to clear the cache.

11. Read directory files (opendir readir closedir)

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

Opens a directory handle that can be used in subsequent closedir(), readdir() and rewinddir() calls.

string readdir ( resource $dir_handle )

Returns the filename of the next file in the directory. File names are returned in order in the file system.

void closedir ( resource $dir_handle )

Close the directory stream specified by dir_handle. The stream must have been previously opened by opendir().

void rewinddir ( resource $dir_handle )

Resets the directory stream specified by dir_handle to the beginning of the directory.

The following is a complete example of reading a directory file:

<?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 files or directories (rename)

bool rename ( oldname, newname, context )

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

Note: The same goes for directories. The system will return the operation result, TRUE if successful, and FALSE if failed.

If you want to move a file or directory, just set the renamed path to the new path, for example:

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

13. Copy (copy) files (copy)

bool copy (source, destination)

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

Note: This operation cannot be performed on the directory; if the target file (/b/1.gif above) already exists, the original file will be overwritten; if you want to move the file, please use the rename() function.

14. Get the free space of the directory (disk_free_space)

disk_free_space ( directory )

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

15. Determine whether the specified file is writable (is_writable or 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命令

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/992746.htmlTechArticlephp文件,文件夹(目录)操作函数总结 本文章来给各位同学总结一下在php中一些常用的文件夹/文件目录操作函数总结,这些只是简单的介绍一...
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

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 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

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,

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

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