Home Backend Development PHP Tutorial PHP目录函数实现创建、读取目录教程实例_php技巧

PHP目录函数实现创建、读取目录教程实例_php技巧

May 17, 2016 am 09:21 AM
php

今天主要介绍在PHP网站开发中文件目录函数的应用。在PHP网站开发中,我们时常需要读取目录文件信息或者创建目录以存放必要的文件,而当目录文件大小超出规定大小时我们又需要删除目录文件,如手工删除目录即费时又费力,我们完全可以通过PHP自带的目录操作函数实现对目录文件的管理。
  本文以实例教程形式讲解如何使用PHP文件目录函数,实例的主要功能:一、利用PHP目录函数创建多个目录,二、在目录下创建文本文件并在文件中写入相关信息,三、递归实现读取(遍历)目录(文件夹)信息并以列表形式列出目录下的所有子目录及文件。
  本实例涉及到文件读写操作,推荐先查看PHP文件读写教程。
  本实例目录结构:PHP执行文件与leapsoulcn目录处在同一级,创建的子目录处在leapsoulcn目录下。
第一步:使用PHP目录函数创建相关目录

复制代码 代码如下:


mkdir("leapsoulcn",0777);
mkdir("leapsoulcn/leapsoul",0777);
mkdir("leapsoulcn/php",0777);
mkdir("leapsoulcn/php/web",0777);
mkdir("leapsoulcn/php/web/test",0777);
?>

说明:在这段代码中,先使用PHP目录函数mkdir创建主目录leapsoulcn,并创建了两个子目录,leapsoul及php,在php目录下创建了web以及test目录。
知识点:mkdir主要用来创建目录,有两个参数:新目录名(注意创建多级目录时,必须包含目录路径),新目录的访问权限,即umask值,第一个数字通常是0,第二个数字指定了所有者特许,第三个数字指定了所有者用户群的特许 ,第四个数字制定了全局特许,可用值如下:
1 = 可执行
2 = 可写
4 = 可读
将三个数字加起来,7代表拥有所有权限,你可以根据自己的需要对创建的新目录赋予不同的权限。
第二步:在leapsoulcn/php/目录下创建leapsoulcn.txt文件,并写入相关的内容
复制代码 代码如下:


@$fp = fopen("leapsoulcn/php/leapsoulcn.txt","w");
if(!$fp){
echo "system error";
exit();
}else {
$fileData = "domain"."\t"."www.jb51.net"."\n";
$fileData = $fileData."description"."\t"."PHP网站开发教程网,面向PHP初学者的PHP教程网。"."\n";
$fileData = $fileData."title"."\t"."本实例主要讲述PHP目录函数的具体应用:涵盖读取目录、创建目录、删除目录等功能";
fwrite($fp,$fileData);
fclose($fp);
}
?>

说明:这段实例代码具体解释可参考之前介绍的PHP文件写入教程。
第三步:读取(遍历)目录名及文本文件名
复制代码 代码如下:


$dir = opendir("leapsoulcn");
while ($fileDir = readdir($dir)) {
if (!strcmp($fileDir,".")||!strcmp($fileDir,"..")) {
continue;
}
echo $fileDir."目录列表:

";
$subDir = "leapsoulcn/".$fileDir;
$dirC = "->";
listSubDir($subDir,$dirC);
}
closedir($dir);
?>

说明:在这段代码实例教程中主要使用了PHP目录函数opendir(),readdir(),closedir()。
知识点:
1、opendir函数用来打开所游览的具体目录,函数参数为目录名,注意,由于在本实例教程中PHP执行文件和游览的主目录处在同一级,所以传递的参数仅仅只是目录名,如果不在同一级或读取多级目录时,需带上具体的目录路径或文件路径。
2、在通过opendir函数读取了主目录后,通过while循环来进一步读取主目录下的多级目录及文件,此处使用的PHP目录函数为readdir,此函数从目录中读取目录或文件名,当没有可读取的目录或文件时,返回False,注意,读取的目录包含.和..,在本实例教程中由于是一级级往下读取目录,所以当读取的目录信息为.和..时跳出本次循环,继续读取下一级目录。
3、在读取完主目录的所有子目录及文件后,通过PHP目录函数closedir来关闭目录句柄,类似于fclose函数关闭文件。
第四步:创建读取(遍历)目录及文件的递归函数
复制代码 代码如下:


function listSubDir($dirInfo,$dirC)
{
if (is_dir($dirInfo)) {
$subDir = dir($dirInfo);
while ($subFile = $subDir->read()) {
if (!strcmp($subFile,".")||!strcmp($subFile,"..")) {
continue;
}
$newDir = $dirInfo."/".$subFile;
if (is_file($newDir)) {
echo $dirC.$subFile.":文件属性
";
}
else{
echo $dirC.$subFile.":目录属性
";
listSubDir($newDir,"-".$dirC);
}
}
$subDir->close();
return;
}
else return;
}
?>

说明:此函数有两个参数:需要读取的目录(包含目录路径),显示用的多级目录分隔符。在这个函数中主要使用了PHP文件目录函数is_dir,is_file,dir类。
知识点:
1、首先通过is_dir来判断要读取的是目录还是文件,此函数的参数和opendir函数类似,注意目录路径问题。
2、如果判断需要读取的是目录,则通过dir目录类来进一步读取其多级子目录,层层递归。dir类所具有的操作函数功能和opendir、readdir、closedir这些PHP目录函数功能一致。
  至此整个创建目录,读取目录的代码实例就算完成了,可列出主目录下的多级子目录名及文本文件名。
如何删除目录?
  删除目录可以使用PHP目录函数rmdir,函数的参数和mkdir函数参数类似,可以使用相对目录路径或绝对目录路径,只是要删除的目录必须为空目录,通过上述代码实例你完全可以判断哪些是空目录。
  通过应用这些基本的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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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

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

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

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