繁体   English   中英

scandir返回目录,但不返回fileq

[英]scandir returns dirs but not fileq

我正在使用scandir来找到一个文件夹,然后在内部检查要在链接中使用的文件。 我使用它来抓取文件夹的位置很好,但是如果我尝试获取文件,它将返回null。

$path = "/path/to/plugin";
$dir = array_diff(scandir($path), array('..', '.'));
$tmpYear = 0;
$tmpMonth = 0;
foreach($dir as $year){
  if((int)$year > $tmpYear){
    $tmpYear = (int)$year;
  }
}
$path2 = $path."/".$tmpYear;
$dir2 = array_diff(scandir($path2), array('..', '.'));
foreach ($dir2 as $month) {
  if((int)$month > $tmpMonth){
    $tmpMonth = (int)$month;
  }
}
$comPath = $path2."/".$tmpMonth;
$dir3 = scandir($comPath);
foreach ($dir3 as $filename) {
    $finalfile = $filename;
}
var_dump($dir3);

这将转储为NULL,但是就像如果我只是var_dump($ dir2)只是一个级别,我将正确获取文件夹名称。

编辑:整个文件/文件夹结构归www-data:www-data所有,我的服务器是运行LEMP堆栈的ubuntu。 所有权限的权限也都设置为766。

为了演示某些Recursive Iterator类的用法,我使用以下代码创建了具有伪文件的目录结构。

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

给出了这样的目录结构:(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

然后在每个子目录结构中,如下所示:(cmd line)

c:\Temp\fileuploads\1\2018>dir /B /OD
1
2
3
4
5
6
7
8
9
10
11
12

每个文件夹都包含一个伪pdf文件,如上所述。


而且,希望我不会误会,以下代码结合使用recursiveDirectoryIteratorRecursiveIteratorIterator从给定的起点浏览所有文件夹-使用isFile方法测试文件而不是目录。

/* 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;
    }
}

从这一点出发,链接的生成应该很简单-希望能有所帮助。

原来我将月份转换为整数,并且删除了文件夹名称中的前导0。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM