在PHP上读取文件名


Filename reading on PHP

我试图从使用代码的目录中读取文件名,并添加一个过滤器,只读文件与当前的年份和月份在文件名中,例如

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

所以代码只会返回文件名中有201305的文件,但它返回一个正确的过滤集,但有些文件缺失,我不知道为什么?

还有什么文件"。"answers".."存储在数组的前2行?

下面是代码

$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);
}

为什么要扫描?使用DirectoryIterator不要害怕使用现代PHP

从手册:

DirectoryIterator类为查看文件系统目录的内容提供了一个简单的接口。

的例子:

<?php
$filenames = array();
$iterator = new DirectoryIterator($directory);
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        $filenames[] = $fileinfo->getFilename();
    }
}
print_r($filenames);
?>

使用DirectoryIterator,您可以通过以下方法检查$fileInfo:

  • DirectoryIterator::isDir -确定当前DirectoryIterator项是否为目录
  • DirectoryIterator::isDot -确定当前DirectoryIterator项是否为'。'或'..'
  • DirectoryIterator::isExecutable -确定当前DirectoryIterator项是否为可执行
  • DirectoryIterator::isFile -确定当前DirectoryIterator项是否为常规文件
  • DirectoryIterator::isLink -确定当前DirectoryIterator项是否为符号链接
  • DirectoryIterator::isReadable -确定当前DirectoryIterator项是否可以读取
  • DirectoryIterator::isWritable -确定当前DirectoryIterator项是否可以写入

正如评论中所说:

.为当前目录..是这个目录上面的目录

你可以跳过这两个来读取目录。

我个人会做的是根据正则表达式读取文件名和信息,如下所示:

$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'];
}

这是未经测试的,我可能过度转义了正则表达式-_


至于你的问题为什么文件可能不可用,我想这个问题属于服务器故障。但是,您可以使用fileperms (http://www.php.net/manual/en/function.fileperms.php)测试文件的权限,但是,当它们首先不可读时,这将无法提供结果。