PHP List All Files in Directory

List all files in one directory PHP

Check this out : readdir()


This bit of code should list all entries in a certain directory:

if ($handle = opendir('.')) {

while (false !== ($entry = readdir($handle))) {

if ($entry != "." && $entry != "..") {

echo "$entry\n";
}
}

closedir($handle);
}

Edit: miah's solution is much more elegant than mine, you should use his solution instead.

How to list directories, sub-directories and all files in php

Use scandir to see all stuff in the directory and is_file to check if the item is file or next directory, if it is directory, repeat the same thing over and over.

So, this is completely new code.

function listIt($path) {
$items = scandir($path);

foreach($items as $item) {

// Ignore the . and .. folders
if($item != "." AND $item != "..") {
if (is_file($path . $item)) {
// this is the file
echo "-> " . $item . "<br>";
} else {
// this is the directory

// do the list it again!
echo "---> " . $item;
echo "<div style='padding-left: 10px'>";
listIt($path . $item . "/");
echo "</div>";
}
}
}
}

echo "<div style='padding-left: 10px'>";
listIt("/");
echo "</div>";

You can see the live demo here in my webserver, btw, I will keep this link just for a second

When you see the "->" it's an file and "-->" is a directory

The pure code with no HTML:

function listIt($path) {
$items = scandir($path);

foreach($items as $item) {
// Ignore the . and .. folders
if($item != "." AND $item != "..") {
if (is_file($path . $item)) {
// this is the file
// Code for file
} else {
// this is the directory
// do the list it again!
// Code for directory
listIt($path . $item . "/");
}
}
}
}

listIt("/");

the demo can take a while to load, it's a lot of items.

How to list all files in folders and sub-folders using scandir and display them as an option in select?

While the other answers are fine and correct, allow me to add my solution as well:

function dirToOptions($path = __DIR__, $level = 0) {
$items = scandir($path);
foreach($items as $item) {
// ignore items strating with a dot (= hidden or nav)
if (strpos($item, '.') === 0) {
continue;
}

$fullPath = $path . DIRECTORY_SEPARATOR . $item;
// add some whitespace to better mimic the file structure
$item = str_repeat(' ', $level * 3) . $item;
// file
if (is_file($fullPath)) {
echo "<option>$item</option>";
}
// dir
else if (is_dir($fullPath)) {
// immediatly close the optgroup to prevent (invalid) nested optgroups
echo "<optgroup label='$item'></optgroup>";
// recursive call to self to add the subitems
dirToOptions($fullPath, $level + 1);
}
}

}

echo '<select>';
dirToOptions();
echo '</select>';

It uses a recursive call to fetch the subitems. Note that I added some whitespace before each item to better mimic the file structure. Also I closed the optgroup immediatly, to prevent ending up with nested optgroup elements, which is invalid HTML.

Getting the names of all files in a directory with PHP

Don't bother with open/readdir and use glob instead:

foreach(glob($log_directory.'/*.*') as $file) {
...
}

List all the files and folders in a Directory with PHP recursive function

Get all the files and folders in a directory, don't call function when you have . or ...

Your code :

<?php
function getDirContents($dir, &$results = array()) {
$files = scandir($dir);

foreach ($files as $key => $value) {
$path = realpath($dir . DIRECTORY_SEPARATOR . $value);
if (!is_dir($path)) {
$results[] = $path;
} else if ($value != "." && $value != "..") {
getDirContents($path, $results);
$results[] = $path;
}
}

return $results;
}

var_dump(getDirContents('/xampp/htdocs/WORK'));

Output (example) :

array (size=12)
0 => string '/xampp/htdocs/WORK/iframe.html' (length=30)
1 => string '/xampp/htdocs/WORK/index.html' (length=29)
2 => string '/xampp/htdocs/WORK/js' (length=21)
3 => string '/xampp/htdocs/WORK/js/btwn.js' (length=29)
4 => string '/xampp/htdocs/WORK/js/qunit' (length=27)
5 => string '/xampp/htdocs/WORK/js/qunit/qunit.css' (length=37)
6 => string '/xampp/htdocs/WORK/js/qunit/qunit.js' (length=36)
7 => string '/xampp/htdocs/WORK/js/unit-test.js' (length=34)
8 => string '/xampp/htdocs/WORK/xxxxx.js' (length=30)
9 => string '/xampp/htdocs/WORK/plane.png' (length=28)
10 => string '/xampp/htdocs/WORK/qunit.html' (length=29)
11 => string '/xampp/htdocs/WORK/styles.less' (length=30)

PHP: List all files in a folder recursively and fast

You could use the RecursiveDirectoryIterator - but I doubt, it's faster than a simple recusive function.

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/path/to/folder'));
foreach ($iterator as $file) {
if ($file->isDir()) continue;
$path = $file->getPathname();
}

How to list files and folder in a dir (PHP)

PHP 5 has the RecursiveDirectoryIterator.

The manual has a basic example:

<?php

$directory = '/system/infomation/';

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

while($it->valid()) {

if (!$it->isDot()) {

echo 'SubPathName: ' . $it->getSubPathName() . "\n";
echo 'SubPath: ' . $it->getSubPath() . "\n";
echo 'Key: ' . $it->key() . "\n\n";
}

$it->next();
}

?>

Edit -- Here's a slightly more advanced example (only slightly) which produces output similar to what you want (i.e. folder names then files).

// Create recursive dir iterator which skips dot folders
$dir = new RecursiveDirectoryIterator('./system/information',
FilesystemIterator::SKIP_DOTS);

// Flatten the recursive iterator, folders come before their files
$it = new RecursiveIteratorIterator($dir,
RecursiveIteratorIterator::SELF_FIRST);

// Maximum depth is 1 level deeper than the base folder
$it->setMaxDepth(1);

// Basic loop displaying different messages based on file or folder
foreach ($it as $fileinfo) {
if ($fileinfo->isDir()) {
printf("Folder - %s\n", $fileinfo->getFilename());
} elseif ($fileinfo->isFile()) {
printf("File From %s - %s\n", $it->getSubPath(), $fileinfo->getFilename());
}
}

PHP list of specific files in a directory

if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'xml')
{
$thelist .= '<li><a href="'.$file.'">'.$file.'</a></li>';
}
}
closedir($handle);
}

A simple way to look at the extension using substr and strrpos

get all file names from a directory in php

I will go ahead and post a sample of code I am currently using, with a few changes, although I would normally tell you to look it up on google and try it first.

if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo $file;
}
closedir($handle);
}

This will display the entire contents of a directory... including: ".", "..", any sub-directories, and any hidden files. I am sure you can figure out a way to hide those if it is not desirable.

List files in a directory with PHP and JavaScript

Extending your code: write the file entries to an array instead of echo ing them right away. Then json_encode that array and finally echo it in your <script> tag

<?php
$files = array();
if ($handle = opendir('./share')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$files[] = $entry;
}
}
closedir($handle);
}
$json = json_encode($files);
// var_dump($json);
?>
<script>
let data = <?php echo $json ?>;
</script>


Related Topics



Leave a reply



Submit