Dex*_*erW 82 php directory filenames file
出于某种原因,我使用以下代码持续获得文件名为'1':
if (is_dir($log_directory))
{
if ($handle = opendir($log_directory))
{
while($file = readdir($handle) !== FALSE)
{
$results_array[] = $file;
}
closedir($handle);
}
}
Run Code Online (Sandbox Code Playgroud)
当我回显$ results_array中的每个元素时,我得到一堆'1',而不是文件的名称.如何获取文件的名称?
Tat*_*nen 160
不要打扰open/readdir glob而是使用:
foreach(glob($log_directory.'/*.*') as $file) {
...
}
Run Code Online (Sandbox Code Playgroud)
Ili*_*ija 46
SPL风格:
foreach (new DirectoryIterator(__DIR__) as $file) {
if ($file->isFile()) {
print $file->getFilename() . "\n";
}
}
Run Code Online (Sandbox Code Playgroud)
检查DirectoryIterator和SplFileInfo类,以获取可以使用的可用方法列表.
Mik*_*ore 18
你需要$file = readdir($handle)用括号括起来.
干得好:
$log_directory = 'your_dir_name_here';
$results_array = array();
if (is_dir($log_directory))
{
if ($handle = opendir($log_directory))
{
//Notice the parentheses I added:
while(($file = readdir($handle)) !== FALSE)
{
$results_array[] = $file;
}
closedir($handle);
}
}
//Output findings
foreach($results_array as $value)
{
echo $value . '<br />';
}
Run Code Online (Sandbox Code Playgroud)
Ali*_*web 12
由于公认的答案有两个重要的缺陷,我正在为那些正在寻找正确答案的新来者发布改进的答案:
foreach (array_filter(glob('/Path/To/*'), 'is_file') as $file)
{
// Do something with $file
}
Run Code Online (Sandbox Code Playgroud)
globe函数结果is_file是必要的,因为它也可能返回一些目录..自己的名字,所以*/*模式一般很糟糕.小智 7
我有更小的代码:
$path = "Pending2Post/";
$files = scandir($path);
foreach ($files as &$value) {
echo "<a href='http://localhost/".$value."' target='_blank' >".$value."</a><br/><br/>";
}
Run Code Online (Sandbox Code Playgroud)
在某些操作系统上,您会获得. ..和.DS_Store,那么我们无法使用它们,因此我们将它们隐藏起来。
首先开始使用获取有关文件的所有信息 scandir()
// Folder where you want to get all files names from
$dir = "uploads/";
/* Hide this */
$hideName = array('.','..','.DS_Store');
// Sort in ascending order - this is default
$files = scandir($dir);
/* While this to there no more files are */
foreach($files as $filename) {
if(!in_array($filename, $hideName)){
/* echo the name of the files */
echo "$filename<br>";
}
}
Run Code Online (Sandbox Code Playgroud)