Ответ 1
Не беспокойтесь о open/readdir и используйте glob
вместо:
foreach(glob($log_directory.'/*.*') as $file) {
...
}
По какой-то причине я продолжаю получать "1" для имен файлов с помощью этого кода:
if (is_dir($log_directory))
{
if ($handle = opendir($log_directory))
{
while($file = readdir($handle) !== FALSE)
{
$results_array[] = $file;
}
closedir($handle);
}
}
Когда я повторяю каждый элемент в $results_array, я получаю кучу '1', а не имя файла. Как получить имя файла?
Не беспокойтесь о open/readdir и используйте glob
вместо:
foreach(glob($log_directory.'/*.*') as $file) {
...
}
SPL style:
foreach (new DirectoryIterator(__DIR__) as $file) {
if ($file->isFile()) {
print $file->getFilename() . "\n";
}
}
Отметьте DirectoryIterator и SplFileInfo классы для списка доступных методов, которые вы можете использовать.
Вам нужно окружить $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 />';
}
Просто используйте glob('*')
. Здесь Документация
Поскольку принятый ответ имеет два важных недостатка, я отправляю улучшенный ответ тем новым посетителям, которые ищут правильный ответ:
foreach (array_filter(glob('/Path/To/*'), 'is_file') as $file)
{
// Do something with $file
}
globe
с помощью is_file
необходима, так как она может также возвращать некоторые каталоги..
в своих именах, поэтому */*
шаблон отстой вообще.У меня есть меньший код для этого:
$path = "Pending2Post/";
$files = scandir($path);
foreach ($files as &$value) {
echo "<a href='http://localhost/".$value."' target='_blank' >".$value."</a><br/><br/>";
}
Это связано с погрешностью оператора. Попробуйте изменить его на:
while(($file = readdir($handle)) !== FALSE)
{
$results_array[] = $file;
}
closedir($handle);
На некоторых ОС вы получаете .
..
и .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>";
}
}
glob()
и FilesystemIterator
примеры:
/*
* glob() examples
*/
// get the array of full paths
$result = glob( 'path/*' );
// get the array of file names
$result = array_map( function( $item ) {
return basename( $item );
}, glob( 'path/*' ) );
/*
* FilesystemIterator examples
*/
// get the array of file names by using FilesystemIterator and array_map()
$result = array_map( function( $item ) {
// $item: SplFileInfo object
return $item->getFilename();
}, iterator_to_array( new FilesystemIterator( 'path' ), false ) );
// get the array of file names by using FilesystemIterator and iterator_apply() filter
$it = new FilesystemIterator( 'path' );
iterator_apply(
$it,
function( $item, &$result ) {
// $item: FilesystemIterator object that points to current element
$result[] = (string) $item;
// The function must return TRUE in order to continue iterating
return true;
},
array( $it, &$result )
);
Вы можете просто попробовать функцию scandir(Path)
. это быстро и легко реализовать
Синтаксис:
$files = scandir("somePath");
Эта функция возвращает список файлов в массив.
чтобы просмотреть результат, вы можете попробовать
var_dump($files);
Или
foreach($files as $file)
{
echo $file."< br>";
}
Другой способ перечислить каталоги и файлы будет использовать RecursiveTreeIterator
, на который вы ответили: fooobar.com/questions/100148/....
Подробное объяснение RecursiveIteratorIterator
и итераторов в PHP можно найти здесь: fooobar.com/questions/77369/...
Вот более продвинутый пример показ всех файлов в папке
Я просто использую этот код:
<?php
$directory = "Images";
echo "<div id='images'><p>$directory ...<p>";
$Files = glob("Images/S*.jpg");
foreach ($Files as $file) {
echo "$file<br>";
}
echo "</div>";
?>
Использование:
if ($handle = opendir("C:\wamp\www\yoursite/download/")) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "<b>" . preg_replace('/\\.[^.\\s]{3,4}$/', '', $entry) . "</b>";
}
}
closedir($handle);
}
Источник: http://chandreshrana.blogspot.com/2016/08/how-to-fetch-all-files-name-from-folder.html
Рекурсивный код для изучения всего файла, содержащегося в каталоге ( "$ path" содержит путь к каталогу):
function explore_directory($path)
{
$scans = scandir($path);
foreach($scans as $scan)
{
$new_path = $path.$scan;
if(is_dir($new_path))
{
$new_path = $new_path."/";
explore_directory($new_path);
}
else // A file
{
/*
Body of code
*/
}
}
}