Recursive Directory Scan/Mapping PHP Function
When one of our clients websites got hacked yesterday a lot of files had injected Javascript that needed to be removed. To quickly remove repeated strings from hundreds of files I whipped up a quick script that recursively scanned a directory and matched “injected” files.
Ignoring the preg matches and the infected files here’s a quick and simple function I thought I’d share. It recursively scans and maps from a set directory to an array in PHP.
Example Output:
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 28 29 30 31 | Array
(
[_session.gif] => _session.gif
[bin] => Array
(
[viewport.js] => viewport.js
)
[datefunctions.js] => datefunctions.js
[forIE] => Array
(
[csshover.htc] => csshover.htc
[htcmime.php] => htcmime.php
[pngbehavior.htc] => pngbehavior.htc
[x.gif] => x.gif
)
[index.html] => index.html
[mootools] => Array
(
[moodx.js] => moodx.js
[moostick.js] => moostick.js
[mootools-info.txt] => mootools-info.txt
[mootools.js] => mootools.js
)
[multifile.js] => multifile.js
[session.js] => session.js
[tablesort.js] => tablesort.js
[tabpane.js] => tabpane.js
) |
PHP Function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | $directory = "../mlab/manager/media/script/"; function recursive($directory) { $dirs = array_diff(scandir($directory), Array( ".", ".." )); $dir_array = Array(); foreach($dirs as $d) { if(is_dir($directory."/".$d)) $dir_array[$d] = recursive($directory."/".$d); else $dir_array[$d] = $d; } return $dir_array; } $structure = recursive($directory); echo "<pre>"; print_r($structure); echo " |
“;