[英]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文件,如上所述。
而且,希望我不會誤會,以下代碼結合使用recursiveDirectoryIterator
和RecursiveIteratorIterator
從給定的起點瀏覽所有文件夾-使用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.