Im trying to read filenames from a directory using the code and adding a filter to readonly files with the current year and month in the filename for example
Julius Robles_Client11_20130508_10-42-42_AM.zip
Julius Robles_Client12_20130508_11-45-42_AM.zip
Julius Robles_Client13_20130508_11-58-42_AM.zip
so the code will only return files with 201305 in their names but it returns a correct filtered set but some files are missing and i dont know why?
also what is the file "." and ".." stored in the first 2 rows of the array?
heres the code
$filenames = array();
if ($handle = opendir('archive/search_logs/')) {
$ctr = 0;
while (false !== ($entry = readdir($handle))) {
//if(strpos($entry,date('Ym')) !== false){
$name = $entry;
$entry = str_replace("-",":",$entry);
$filenames[$ctr] = explode("_", $entry);
$filenames[$ctr][] = $name;
$ctr++;
//}
}
closedir($handle);
}
why scandir? Use DirectoryIterator don't be affraid to use modern PHP
from manual:
The DirectoryIterator class provides a simple interface for viewing the contents of filesystem directories.
example:
<?php
$filenames = array();
$iterator = new DirectoryIterator($directory);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
$filenames[] = $fileinfo->getFilename();
}
}
print_r($filenames);
?>
with DirectoryIterator you can check $fileInfo via this methods:
As said in the comment:
.
is the current directory ..
is the directory above this one
You can skip both for reading the directory.
What I would personally do is read the filename and information based on a regular expression like so:
$filenames = array();
foreach( scandir( 'archive/search_logs/' ) as $file ) {
// test for current or higher path
if( $file == "." || $file == ".." ) continue;
// test if readable
if( !is_readable( $file )) printf( "File %s is not readable",$file);
// use regular expression to match: <filename><date:yyyymmdd>_<hours:hh>-<minutes:mm>-<seconds:ss>_<am|pm>.zip
preg_match( "/(?<filename>[.]+)(?<date>[0-9]{8})\_(?<hours>[0-9]{2})\-(?<minutes>[0-9]{2})\-(?<seconds>[0-9]{2})\_(?<ampm>AM|PM)\.zip$/i" , $file , $matches );
// now use anything in matches that suits your needs:
echo $matches['filename'];
echo $matches['date'];
echo $matches['hours'];
echo $matches['seconds'];
echo $matches['ampm'];
}
This is untested and I might have overdone escaping the regular expression -
and _
.
As to your question why the file might not be available, I guess that question belongs to Server Fault. However you can test files for their rights with fileperms
(http://www.php.net/manual/en/function.fileperms.php), however that will not provide results when they aren't readable in the first place.