search
HomeBackend DevelopmentPHP TutorialChapter 6 PHP Directory and File Operation_PHP Tutorial

Chapter 6 PHP Directory and File Operation_PHP Tutorial

Jul 21, 2016 pm 03:21 PM
basenamedirnamephponeandoperatedocumentfile nameTable of contentschapterpathreturnpart

one. Directory operations
basename -- Returns the file name part of the path
dirname -- Returns the directory part of the path
pathinfo -- Returns file path information
realpath -- Returns the normalized absolute path name

Copy code The code is as follows:

$path = 'demo1.php';
$path = realpath($path);
echo basename($path);
echo '
';
echo dirname($path);
echo '
';
$array_path = pathinfo($path);
echo 'basename : '.$array_path['basename'].'
';
echo 'dirname : '.$array_path[ 'dirname'].'
';
echo 'extension : '.$array_path['extension'].'
';
echo 'filename : '.$array_path['filename '].'
';
?>

Output:
demo1.php
D:AppServwwwBasic6
basename : demo1.php
dirname: D:AppServwwwBasic6
extension: php
filename: demo1

2. Disk, directory and file count
1. View file size and disk space
filesize -- Get the file size
disk_free_space -- Return the available space in the directory
disk_total_space -- Return the total disk space of a directory Size
Copy code The code is as follows:

$path ='demo2.php';
$path = realpath($path);
$drive = 'c:';
echo round(filesize($path)/1024,2).'kb'.'
';
echo round(disk_free_space($drive)/1024/1024/1024,2).'GB'.'
';
echo round(disk_total_space($drive)/1024/ 1024/1024,2).'GB'.'
';
?>

output
0.26kb
10.61GB
30.01 GB

2. Get various times of files
fileatime -- Get the last access time of the file
filectime -- Get the inode modification time of the file
filemtime -- Get the file modification time
Copy code The code is as follows:

$file = realpath ( '../Basic5/ demo3.php' );
$date_format = 'Y-m-d h:i:s';
echo 'lastest accessing time : '.date ( $date_format, fileatime ( $file ) ) . '
' ;
echo 'lastest change time : '.date ( $date_format, filectime ( $file ) ) . '
';
echo 'lastest modify time : '.date ( $date_format, filemtime ( $ file ) ) . '
';
?>

output
lastest accessing time : 2011-12-18 04:26:49
lastest change time : 2011-12-18 04:26:49
lastest modify time : 2011-12-18 04:29:15

三.文件处理
文件读写的两种方式:
1.php所有版本都支持的方法:
fopen -- 打开文件或者 URL
fclose -- 关闭一个已打开的文件指针
fwrite -- 写入文件(可安全用于二进制文件)
表 1. fopen() 中 mode 的可能值列表

mode

说明

'r'

只读方式打开,将文件指针指向文件头。

'r+'

读写方式打开,将文件指针指向文件头。

'w'

写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。

'w+'

读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。

'a'

写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。

'a+'

读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。

'x'

创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。此选项被 PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。

'x+'

创建并以读写方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 FALSE,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。此选项被 PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。

复制代码 代码如下:

$fp = fopen('file1.txt','w');
$outStr = "my name is anllin,\r\nmy age is 29.";
fwrite($fp,$outStr,strlen($outStr));
fclose($fp);
?>

output
my name is anllin,
my age is 29.
2.php5新加入的方法
file_put_contents -- 将一个字符串写入文件
复制代码 代码如下:

file_put_contents('file2.txt',"my name is anllin,\r\nmy age is 29.");
?>

output
my name is anllin,
my age is 29.
读出文件内容的方法:

函数

功能

Fgetc()

读出一个字符,并将指针移到下一个字符

Fgets()

读出一行字符,可以指定一行显示的长度。

Fgetss()

从文件指针中读取一行并过滤掉HTML标记

Fread()

读取定量的字符

Fpassthru()

输出文件到指定处的所有剩余数据

File()

将整个文件读入数组中,以行分组

Readfile()

读入一个文件并写入到输出缓冲

File_get_contents()

将整个文件读入一个字符串

Feof()

判断读完文件函数

File_exists()

查看文件是否存在

The content of the sample file file1.txt is as follows:
my name is anllin,
my age is 29.
fgetc -- Read characters from the file pointer
Demo.php
Copy code The code is as follows:

$fp = fopen('file1.txt','r');
echo fgetc($fp);
echo fgetc($fp);
fclose($fp);
?>

Output:
my
fgets -- Read a line from the file pointer
Copy the code The code is as follows:

$fp = fopen('file1.txt','r');
echo fgets($fp);
echo fgets($fp);
fclose($fp);
? >

output
my name is anllin, my age is 29.
fgetss -- Read a line from the file pointer and filter out HTML tags
Copy code The code is as follows:

$fp = fopen('file3.txt','w');
$outStr = "my name is anllin";
fwrite($fp,$outStr,strlen($outStr));
fclose($fp);
$ ftp = fopen('file3.txt','r');
echo fgetss($ftp);
fclose($ftp);
?>

Output
my name is anllin
fread -- read file (safe for binary files)
Copy code The code is as follows:

$filename = 'file1.txt';
$fp = fopen($filename,'r');
$contents = fread($fp,filesize ($filename));
echo $contents;
fclose($fp);
?>

Output
my name is anllin, my age is 29 .
fpassthru -- Output all remaining data at the file pointer
Copy code The code is as follows:

php
$filename = 'file1.txt';
$fp = fopen($filename,'rb');
$leftSize = fpassthru($fp);
echo $leftSize;
fclose($fp);
?>

output
my name is anllin, my age is 29. 33
file -- Read the entire file into an array In
Copy code The code is as follows:

$lines = file('file1.txt' );
foreach ($lines as $line_num => $line)
{
echo $line_num.' : '.$line.'
';
}
?>

output
0 : my name is anllin,
1 : my age is 29.
readfile -- Output a file
Copy code The code is as follows:

$size = readfile('file1.txt');
echo $size;
?>

output
my name is anllin, my age is 29.33
file_get_contents -- Read the entire file into a string (new in php5.0)
Copy code The code is as follows:

$contents = file_get_contents('file1.txt');
echo $contents;
?>

output
my name is anllin, my age is 29.
feof -- test whether the file pointer reaches the end of the file Location
Copy code The code is as follows:

$fp = fopen('file1.txt' ,'r');
while(!feof($fp))
{
echo fgetc($fp);
}
fclose($fp);
?> ;

output
my name is anllin, my age is 29.
file_exists -- Check whether the file or directory exists
Copy code The code is as follows:


< ;?php
$filename = 'file1.txt';
if(file_exists($filename))
{
echo 'Perform file read and write operations';
}
else
{
echo 'The file you are looking for does not exist';
}
?>

output
Perform file read and write operations
filesize -- Get the file size
Copy code The code is as follows:

$file_size = filesize(' file1.txt');
echo $file_size;
?>

output
33
unlink -- 删除文件
复制代码 代码如下:

$isDeleted = unlink('file3.txt');
echo $isDeleted;
?>

output
1
rewind -- 倒回文件指针的位置
ftell -- 返回文件指针读/写的位置
fseek -- 在文件指针中定位
复制代码 代码如下:

$fp = fopen ( 'file1.txt', 'r' );
fgetc ( $fp );
fgetc ( $fp );
echo ftell ( $fp ) . '
';
rewind ( $fp );
echo ftell ( $fp ) . '
';
fgetc ( $fp );
fgetc ( $fp );
echo ftell ( $fp ) . '
';
fseek($fp,0);//same as rewind ($fp)
echo ftell ( $fp ) . '
';
?>

output
2
0
2
0
Flock的操作值

操作值

意义

LOCK_SH(以前为1)

读写锁定。这意味着文件可以共享,其他人可以读该文件

LOCK_EX(以前为2)

写操作锁定。这是互斥的,该文件不能被共享

LOCK_UN(以前为3)

释放已有的锁定

LOCK_NB(以前为4)

防止在请求加锁时发生阻塞

flock -- lightweight consultation file locking
Copy code The code is as follows:

$filename = 'file1.txt';
$fp = fopen($filename,'rb');
flock($fp,LOCK_EX);//locked
$contents = fread($fp,filesize($ filename));
flock($fp,LOCK_UN);//unlocked
echo $contents;
fclose($fp);
?>

output
my name is anllin, my age is 29.
Directory handle operations
opendir -- open the directory handle
readdir -- read entries from the directory handle
closedir -- close the directory handle
Copy code The code is as follows:

$dir= opendir('../Basic6' );
while(!!$file = readdir($dir))
{
echo $file.'
';
}
closedir($dir) ;
?>

output
.
..
.buildpath
.project
.settings
demo1.php
demo10.php
demo11.php
demo12.php
demo13.php
demo14.php
demo15.php
demo16.php
demo17.php
demo18. php
demo19.php
demo2.php
demo20.php
demo3.php
demo4.php
demo5.php
demo6.php
demo7.php
demo8.php
demo9.php
file1.txt
file2.txt
scandir -- List files and directories in the specified path
Copy the code The code is as follows:

$files = scandir('../Basic6');
foreach($files as $file )
{
echo $file.'
';
}
?>

output
.
..
.buildpath
.project
.settings
demo1.php
demo10.php
demo11.php
demo12.php
demo13.php
demo14.php
demo15.php
demo16.php
demo17.php
demo18.php
demo19.php
demo2.php
demo20.php
demo21.php
demo3.php
demo4.php
demo5.php
demo6.php
demo7.php
demo8.php
demo9.php
file1.txt
file2. txt
rename -- Rename a file or directory
Copy code The code is as follows:

rename('demo1.php','demo01.php');
if(file_exists('demo01.php'))
{
echo 'file rename success';
}
else
{
echo 'file rename fail';
}
?>

output
file rename success
rmdir -- Delete Directory
Copy code The code is as follows:

rmdir('123');
if(file_exists('123'))
{
echo 'delete file fail';
}
{
echo 'delete file success';
}
?> ;

output
delete file success

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324803.htmlTechArticle1. Directory operation basename -- returns the file name part of the path dirname -- returns the directory part of the path pathinfo -- returns the information of the file path realpath -- returns the normalized absolute...
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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software