Jurgen
Jurgen

Reputation: 274

PHP - Scanning through folders and including a file if some conditions match

Let's say I have a starting point folder called scan_inside. In the folder there are lots of sub-folders and in those sub-folders there might be even more folders with some content.

I would like to scan through all the folders and insert a file uploadme.xml if there is an index.htm file found in the current destination. How can I achieve this?

Illustration:

Scanning...

Upvotes: 0

Views: 46

Answers (2)

Jurgen
Jurgen

Reputation: 274

I have updated the code a bit. It seeks for .php files and uploads an uploadme.xml to the same path. Seems to work quite alright but there might be some mistakes, though.

    function scanThroughDir($dir) {
        $result = [];
        foreach(scandir($dir) as $filename) {
            if ($filename[0] === '.') continue;
            $filePath = $dir . '/' . $filename;
            if (is_dir($filePath)) {
                foreach (scanThroughDir($filePath) as $childFilename) {
                    $fileNameParts = explode('.', $childFilename);
                    if(end($fileNameParts) == "php"){
                        copy('uploadme.xml', pathinfo($filePath, PATHINFO_DIRNAME).'/uploadme.xml');
                        $result[] = $childFilename;
                    }
                }
            } else {
                $fileNameParts = explode('.', $filename);
                if(end($fileNameParts) == "php"){
                    copy('uploadme.xml', pathinfo($filePath, PATHINFO_DIRNAME).'/uploadme.xml');
                }
            }
        }
        return $result;
    }

scanThroughDir("mainfolder");

Upvotes: 0

Tiffany
Tiffany

Reputation: 503

First, you need recursion, then you can go through all of the files and try to capture the extension. After that, you can add a file to the array.

function scanThroughDir($dir) {
    $result = [];
    foreach(scandir($dir) as $filename) {
        if ($filename[0] === '.') continue;
        $filePath = $dir . '/' . $filename;
        if (is_dir($filePath)) {
            foreach (scanThroughDir($filePath) as $childFilename) {
                $fileNameParts = explode('.', $childFilename);

                if(end($fileNameParts) == "xml"){
                    echo end($fileNameParts);
                    $result[] = $childFilename;
                }
            }
        } else {
            $fileNameParts = explode('.', $filename);
            if(end($fileNameParts) == "xml"){
                $result[] = $filename;
            }
        }
    }
    return $result;
}

Usage

print_r(scanThroughDir("./"));

Upvotes: 1

Related Questions