To demonstrate the use of some of the Recursive Iterator
classes I used the following code to create a directory structure with dummy files.
function createpath( $path=NULL, $perm=0644 ) {
if( !file_exists( $path ) ) {
createpath( dirname( $path ) );
mkdir( $path, $perm, TRUE );
clearstatcache();
}
}
foreach( range( 2000, 2018 ) as $yr ){
for( $i=1; $i < 13; $i++ ){
$path=$dir . $yr . '/' . $i;
createpath( $path );
file_put_contents( $path .'/pseudo_pdf_file__'.$i.'.pdf.txt', 'Hello World '.$i );
}
}
Which gave a directory structure like this: ( cmd line )
c:\Temp\fileuploads\1>dir /B
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
And then within each a sub-directory structure like this: ( cmd line )
c:\Temp\fileuploads\1\2018>dir /B /OD
1
2
3
4
5
6
7
8
9
10
11
12
With each of these folders containing a pseudo pdf file as named above.
And, hopefully I did not misunderstand, the following uses a recursiveDirectoryIterator
in conjunction with a RecursiveIteratorIterator
to work through all folders from a given starting point - using the isFile
method to test for files rather than directories.
/* all files found will be added to this array */
$files=array();
$pttn='@(\.pdf)@';
/* the start directory for the search */
$dir='c:/temp/fileuploads/1/';
/* create the directory iterator */
$dirItr=new RecursiveDirectoryIterator( $dir, RecursiveDirectoryIterator::KEY_AS_PATHNAME );
/* use a recursive iterator to iterate through directories */
foreach( new RecursiveIteratorIterator( $dirItr, RecursiveIteratorIterator::CHILD_FIRST ) as $obj => $info ) {
/* As it is files you wish to find, use `isFile()` method */
if( $info->isFile() ){
/* Match file name against basic patter to test for .pdf files */
preg_match( $pttn, $info->getFileName(), $col );
/* Add matching files to the output array */
if( !empty( $col ) ){
$files[]=str_replace( realpath( $dir ),'', realpath( $info->getPathName() ) );
}
}
}
/* If any files were found, process the output array */
if( !empty( $files ) ){
foreach( $files as $file ){
/* do stuff with $file */
echo $file;
}
}
From this point the generation of links should be straightforward - hope this helps.