简体   繁体   中英

How to scan a directory and all subdirectorys for specific files (with .php extension)

I've got a folder structure like this:

Examplefolder
|---Folder1
|       |--- file1.php
|---Folder2
|       |---Subfolder
|              |--- subfile1.php
|              |--- subfile2.html
|---Folder3
|---file2.php

As you can see examplefolder is the main folder. It can contain normal php oder oder fileextensions. Inside the main folder there are also subfolders (like folder1 and folder2). An inside the subfolders there can be more folders.

Now I want to scan the examplefolder for files with the extension .php which should get saved into an array. How will this work? I also tried a method witch shows all files, but I want only the files with the php extension.

My example looks like this:

if (file_exists($path) && is_dir($path))
        {
            $result = scandir($path);

            $files = array_diff($result, array('.', '..'));

            if (count($files) > 0)
            {


                foreach ($files as $file)
                {
                    if (is_file("$path/$file"))
                    {
                        $array[] = $file;
                    }
                    else if (is_dir("$path/$file"))
                    {
                        $array[] = $this->getComponentPathNames("$path/$file");
                    }
                }
            }
        }

This is possible with a simple if statement using the substr() function to fetch the last 4 characters of the file name. Like so:

$file = "test-file.php";

if ((substr($file, -4)) == ".php") {
    echo "This";
} else {
    echo "this one";
}

So if the last 4 characters are equal to .php, proceed otherwise do something else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM