search
HomeBackend DevelopmentPHP TutorialBasic operations of directories and files 1 (44)

Resolve directory path

Using PHP scripts can facilitate directory operations, such as creating directories, traversing directories, revaluing directories, and deleting directories.
??Commonly used file directory path format:
??$unixPath="/var/www/html/index.php";
//Absolute paths in UNIX systems must be separated by "/"
??$ winPath="C:\Appserv\www\index.php";
//Absolute path in Windows system, separated by "" by default
??$winPath2="C:/Appserv/www/index.php";
//In Windows systems, "/" can also be used to separate.
??Pay attention to using absolute paths and relative paths.

PHP file path related functions

??basename--returns the file name part of the path

??Syntax: string basename( string path [, string suffix] )
??gives a file containing a pointer to a file A string of full path, this function returns the basic file name. If the file name ends with suffix, this part will also be removed.
??dirname--returns the directory part of the path
??Syntax: string dirname(string path)
??Given a string containing the full path to a file, this function returns the directory after removing the file name name.
$path= "/home/httpd/html/index.php";
$file= basename($path);// $file value: "index.php"
$file= basename($ path, ".php"); // $file value: "index "
$file= dirname($path); // $file value: "/home/httpd/html"
?>

pathinfo-- Return file path information
?? Syntax: array pathinfo( string path [, intoptions] )
??pathinfo() Returns an associative array containing path information. Includes the following array units: dirname, basename and extension.
$path_parts= pathinfo("/www/htdocs/index.html");
echo $path_parts["dirname"] . "n"; // /www/htdocs
echo $path_parts["basename "] . "n"; // index.html
echo $path_parts["extension"] . "n"; // html
?>
??realpath--returns the normalized absolute path name
?? Syntax: string realpath( string path )
??realpath() expands all symbolic links and processes '/./', '/../' and redundant '/' in the input path and returns the normalized absolute path name . There are no symbolic links, '/./' or '/../' components in the returned path.

Traverse the directory

opendir--open the directory handle
??Syntax: resource opendir( string path [, resource context] )
??Open a directory handle, which can be used for subsequent closedir(), readdir() and rewinddir( ) is calling.
??readdir--read entries from the directory handle
??Syntax: string readdir(resource dir_handle)
??Returns the file name at the current directory pointer position, does not return false, and moves the pointer down one bit. File names are returned in order in the file system.
??closedir--close the directory handle
??Syntax: void closedir(resource dir_handle)
??Close the directory stream specified by dir_handle. The stream must have been previously opened by opendir().
??rewinddir--rewind directory handle
??Syntax: void rewinddir(resource dir_handle)
??Reset the directory stream specified by dir_handle to the beginning of the directory.

Statistics directory size

??disk_free_space--returns the available space in the directory
??Syntax: float disk_free_space(string directory)
??Given a string containing a directory, this function will based on the corresponding file System or disk partition returns the number of bytes available.
??disk_total_space--returns the total disk size of a directory
??Syntax: float disk_total_space(string directory)
??Given a string containing a directory, this function will return according to the corresponding file system or disk partition All bytes.

Example

<?php <span>//<span>自定义一个函数dirSize(),统计传入参数的目录大小</span><span>function dirSize($directory) {
$dir_size</span>=<span>0</span>;<span>//</span><span>初值为0,用来累加各文件大小从而计算目录大小</span><span>if</span>($dir_handle=@opendir($directory)){ <span>//</span><span>打开目录并判断成功打开</span><span>while</span>($filename=readdir($dir_handle)) { <span>//</span><span>循环遍历目录</span><span>if</span>($filename!=<span>"</span><span>.</span><span>"</span> && $filename!=<span>"</span><span>..</span><span>"</span>) { <span>//</span><span>排除特殊的目录</span>$subFile=$directory.<span>"</span><span>/</span><span>"</span>.$filename; <span>//</span><span>将文件和目录相连</span><span>if</span>(is_dir($subFile)) <span>//</span><span>如果为目录</span>$dir_size+=dirSize($subFile); <span>//</span><span>求子目录的大小</span><span>if</span>(is_file($subFile)) <span>//</span><span>如果是文件</span>$dir_size+=filesize($subFile); <span>//</span><span>求出文件的大小并累加</span><span>}
}
closedir($dir_handle); </span><span>//</span><span>关闭文件资源</span><span>return</span> $dir_size; <span>//</span><span>返回计算后的目录大小</span><span>}
}
$dir_size</span>=dirSize(<span>"</span><span>phpMyAdmin</span><span>"</span>); <span>//</span><span>调函数计算目录大小,返回目录大小</span>echo round($dir_size/pow(<span>1024</span>,<span>1</span>),<span>2</span>).<span>"</span><span>KB</span><span>"</span>;<span>//</span><span>将目录字节换为“KB”单位</span>?>

Create and delete directories

mkdir--New directory
??Syntax: boostkdir(string pathname [,intmode])
??Try to create a new directory specified by pathname.
??rmdir--Delete directory
??Syntax: boolrmdir(string dirname)
??Try to delete the directory specified by dirname. The directory must be empty and must have appropriate permissions. Returns TRUE if successful, FALSE if failed.
??unlink--Delete file
??Syntax: boolunlink (string filename)
??Delete filename. Similar to Unix C's unlink() function. Returns TRUE if successful, FALSE if failed

<?php <span>//<span>自定义函数递归的删除整个目录</span><span>function delDir($directory) {
</span><span>if</span>(file_exists($directory)) { <span>//</span><span>判断目录是否存在,如果存在则执行</span><span>if</span>($dir_handle=@opendir($directory)){ <span>//</span><span>打开返回目录资源,并判断</span><span>while</span>($filename=readdir($dir_handle)){ <span>//</span><span>遍历目录读出目录中信息</span><span>if</span>($filename!=<span>"</span><span>.</span><span>"</span> && $filename!=<span>"</span><span>..</span><span>"</span>) { <span>//</span><span>一定要排除两个特殊目录</span>$subFile=$directory.<span>"</span><span>/</span><span>"</span>.$filename;<span>//</span><span>将目录下文件和当前目录相连</span><span>if</span>(is_dir($subFile)) <span>//</span><span>如果是目录条件则成立</span>delDir($subFile); <span>//</span><span>递归调用自己删除子目录</span><span>if</span>(is_file($subFile)) <span>//</span><span>如果是文件条件则成立</span>unlink($subFile); <span>//</span><span>直接删除这个文件</span><span>}
}
closedir($dir_handle); </span><span>//</span><span>关闭目录资源</span>rmdir($directory); <span>//</span><span>删除空目录</span><span>}
}
}
delDir(</span><span>"</span><span>phpMyAdmin</span><span>"</span>); <span>//</span><span>调用函数,将程序所在目录中phpMyAdmin文件夹删除</span>?>

Copy and move directories

copy--copy files
??Syntax: boolcopy (string source, string dest)
??Copy files from source to dest. Returns TRUE if successful, FALSE if failed.
??There are no functions related to copying and moving directories in PHP. If necessary, just customize the function.

Basic operations of files

Opening and closing files

fopen--打开文件或者URL
??语法:resource fopen( string filename, string mode [, booluse_include_path[, resource zcontext]] )
??fopen() 将filename指定的名字资源绑定到一个流上。如果filename是"scheme://..." 的格式,则被当成一个URL,PHP 将搜索协议处理器(也被称为封装协议)来处理此模式。如果该协议尚未注册封装协议,PHP 将发出一条消息来帮助检查脚本中潜在的问题并将filename当成一个普通的文件名继续执行下去。
??mode参数指定了所要求到该流的访问类型。
??如果也需要在include_path中搜寻文件的话,可以将可选的第三个参数use_include_path设为'1' 或TRUE。
??如果打开失败,本函数返回FALSE。
fclose--关闭一个已打开的文件指针

写入文件

fwrite--写入文件(可安全用于二进制文件)
??语法:intfwrite( resource handle, string string[, intlength] )
??fwrite() 把string的内容写入文件指针handle处。如果指定了length,当写入了length个字节或者写完了string以后,写入就会停止,视乎先碰到哪种情况。返回写入的字符数,出现错误时则返回FALSE

读取文件内容

??fread--读取文件(可安全用于二进制文件)
??string fread( inthandle, intlength )
??fread() 从文件指针handle读取最多length个字节。该函数在读取完length个字节数,或到达EOF 的时候,或(对于网络流)当一个包可用时就会停止读取文件,视乎先碰到哪种情况。

<span>php
$handle </span>= fopen(<span>"</span><span>http://www.example.com/</span><span>"</span>, <span>"</span><span>rb</span><span>"</span><span>);
$contents </span>= <span>""</span><span>;
</span><span>while</span> (!<span>feof($handle)) {
$contents .</span>= fread($handle, <span>8192</span><span>);
}
fclose($handle);
</span>?>

fgets--从文件指针中读取一行
??语法:string fgets( inthandle [,intlength])
??从handle指向的文件中读取一行并返回长度最多为length-1 字节的字符串。碰到换行符(包括在返回值中)、EOF 或者已经读取了length -1 字节后停止(看先碰到那一种情况)。如果没有指定length,则默认为1K,或者说1024 字节。
??fgetc--从文件指针中读取字符
??语法:string fgetc( resource handle )
??返回一个包含有一个字符的字符串,该字符从handle指向的文件中得到。碰到EOF 则返回FALSE。

file--把整个文件读入一个数组中
??语法:array file ( string filename [, intuse_include_path[, resource context]] )
??和readfile()一样,只除了file() 将文件作为一个数组返回。数组中的每个单元都是文件中相应的一行,包括换行符在内。如果失败file() 返回FALSE。
??readfile--输出一个文件
??语法:intreadfile( string filename [, booluse_include_path[, resource context]] )
??读入一个文件并写入到输出缓冲。
??返回从文件中读入的字节数。如果出错返回FALSE 并且除非是以@readfile() 形式调用,否则会显示错误信息。

以上就介绍了目录与文件的基本操作一 (44),包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

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
PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 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: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 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.

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.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 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

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function