Solved

PHP: Recursive FilesystemIterator

Posted on 2016-10-06
2
54 Views
Last Modified: 2016-10-07
How can I make this recursive?  
Now it only finds files in the "courses" directory.  I want it to also look in sub-directories.

$filesKits=array();
$regex = "/[a-zA-Z]+[\)]?+[0-9]+[e]?\.zip$/";
$path = 'files/courses';
$iterator = new FilesystemIterator($path, FilesystemIterator::SKIP_DOTS + FilesystemIterator::CURRENT_AS_PATHNAME + FilesystemIterator::KEY_AS_FILENAME);
foreach ($iterator as $key => $filepath) {
  if (preg_match($regex, $key)) {
    $filesKits[] = $filepath;
  }
}
0
Comment
Question by:skij
2 Comments
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 41832560
Here's an example that you might be able to tailor for your needs.  You would run it with a URL like this (but I am not leaving something like this on my server):
https://iconoun.com/demo/find_files.php?q=/error_log/i
<?php // demo/find_files.php
/**
 * Put this script in the target root directory
 *
 * Traverse all directories down the web tree
 * Show all files that match the ?q={REGEX} URL argument pattern
 *
 * http://php.net/manual/en/class.recursivedirectoryiterator.php#85805
 */
ob_start();
error_reporting(E_ALL);


// START IN THE CURRENT DIRECTORY
$path = realpath(getcwd());

// THE FILE NAME PATTERN
$regex   = $_GET['q'];
if (empty($regex)) trigger_error("Missing q= URL Argument; please specify the REGEX for the file name.", E_USER_ERROR);
$p_regex = htmlentities($regex);

// COLLECT THE DIRECTORY INFORMATION OBJECTS
$objs = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);


// ITERATE OVER THE OBJECTS
foreach($objs as $name => $obj)
{
    // PROCESS THE MATCHED FILE NAME(S) ONLY
    if (preg_match($regex, $name))
    {
        echo PHP_EOL . "<br>$name";
    }
}


// IF THERE ARE NO MATCHING FILE(S)
$out = ob_get_clean();
if (empty($out))
{
    echo "<h3>No match for $p_regex found.</h3>";
}
else
{
    echo "<h3>Files matching regex: <i>$p_regex</i></h3>";
}


// SHOW THE GIT BRANCH
$root = '.git/HEAD';
$text = @file_get_contents($root);
if ($text)
{
    $text = explode(DIRECTORY_SEPARATOR, $text);
    $text = array_slice($text, 2);
    $name = implode(DIRECTORY_SEPARATOR, $text);
    echo PHP_EOL . "<br>On Git branch: $name" . PHP_EOL;
}
else
{
    echo PHP_EOL . "<br>On Git branch: UNKNOWN" . PHP_EOL;
}


// REPORT THE FILES
echo $out;

Open in new window

0
 
LVL 52

Accepted Solution

by:
Julian Hansen earned 250 total points
ID: 41832751
<?php
$path = dirname(__FILE__);
$regex = '/[a-zA-Z]+[\)]?+[0-9]+[e]?\.zip$/';
$result = array();
findAll($path, $regex, $result);
echo "<pre>" . print_r($result, true) . "</pre>";

function findAll($path, $pattern, &$result) 
{
  $iterator = new FilesystemIterator($path, FilesystemIterator::SKIP_DOTS + FilesystemIterator::CURRENT_AS_PATHNAME + FilesystemIterator::KEY_AS_FILENAME);
  foreach ($iterator as $key => $filepath) {
    if (is_dir($filepath)) {
      findAll($filepath, $pattern, $result);
    }
    else {
      if (preg_match($pattern, $key)) {
        $result[] = $filepath;
      }
    }
  }
}

Open in new window

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Parts and Products table schema in mysql 6 44
wamp versus xampp 4 45
WordPress syntax 2 27
How to convert my query to the proper format? 5 18
Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now