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 Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools