Home php教程 php手册 使用PHP目录函数实现创建、读取目录教程实例

使用PHP目录函数实现创建、读取目录教程实例

Jun 21, 2016 am 08:53 AM
nbsp php quot

  今天主要介绍在PHP网站开发中文件目录函数的应用。在PHP网站开发中,我们时常需要读取目录文件信息或者创建目录以存放必要的文件,而当目录文件大小超出规定大小时我们又需要删除目录文件,如手工删除目录即费时又费力,我们完全可以通过PHP自带的目录操作函数实现对目录文件的管理。

  本文以实例教程形式讲解如何使用PHP文件目录函数,实例的主要功能:一、利用PHP目录函数创建多个目录,二、在目录下创建文本文件并在文件中写入相关信息,三、递归实现读取(遍历)目录(文件夹)信息并以列表形式列出目录下的所有子目录及文件。

  本实例涉及到文件读写操作,推荐先查看PHP文件读写教程。

  本实例目录结构:PHP执行文件与leapsoulcn目录处在同一级,创建的子目录处在leapsoulcn目录下。

第一步:使用PHP目录函数创建相关目录

1
2
3
4
5
6
7
8
9
10
11


    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文件,并写入相关的内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14


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

说明:这段实例代码具体解释可参考之前介绍的PHP文件写入教程。

第三步:读取(遍历)目录名及文本文件名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17


    $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函数关闭文件。

第四步:创建读取(遍历)目录及文件的递归函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27


    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目录函数及文件操作函数,完全可以实现和文件系统打交道,自行编写一个具有创建、删除目录、读取目录、管理文件的网站目录文件管理系统,那文件信息、文件大小如何读取?删除或移动文件如何实现?呵呵,我们下次分享吧。

  :PHP网站开发教程-leapsoul.cn版权所有,转载时请以链接形式注明原始出处及本声明,谢谢。



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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks 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)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles