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 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.
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.
PHP: Get list of all filenames contained within my images directory
Try glob
Something like:
foreach(glob('./images/*.*') as $filename){
echo $filename;
}
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)
Get filename from each folder (like nested) using PHP
you can use scandir to get the list of all files in a given directory.
So, your code be changed like this:
$dir = "Car_Brands";
$dh = opendir($dir);
while (false !== ($subdir = readdir($dh)))
{
$fileList = scandir($dir.'/'.$subdir);
$files[] = $fileList[2];
}
natcasesort($files);
foreach ($files as $file)
{
if($file!='.' && $file!='..')
{
echo $file;
}
}
scandir() returns an array that contains the list of all the files in the given directory. If you are in linux server and you are sure each of your directory has one file only, you should get your file name from the 3rd index of the Array, which is $fileList[2]
in our case. It is the 3rd index cause if you do a var dump of the array that scandir() returns you will see something like below:
Array
(
[0] => .
[1] => ..
[2] => alto.php
)
I would recommend you to do a print_r($fileList)
within your loop, that will give you a better idea on what index to look at.
Update
You can also use glob. In that case your code will look like the below:
$dir = "Car_Brands";
$dh = opendir($dir);
while (false !== ($dirname = readdir($dh)))
{
if ($dirname == '..' || $dirname == '.') {
continue;
}
$subdir = $dir.'/'.$dirname.'/';
$ext = '*.php';
$fileList = glob($subdir.$ext);
if (!empty($fileList)) {
$files[] = $fileList[0];
// The above line will return the whole path. (eg. car_brands/AAA/alto.php)
// if you want the file name only (eg. alto.php) use the below line instead
// $files[] = str_replace($subdir, '', $fileList[0]);
}
}
natcasesort($files);
foreach ($files as $file)
{
echo $file;
}
How to use php to retrieve all the file name in a specific folder
There are many ways of retrieving folder content like glob
, scandir
, DirectoryIterator
and RecursiveDirectoryIterator
, personaly I would recommend you to check DirectoryIterator as it has big potential.
Example using scandir
method
$dirname = getcwd();
$dir = scandir($dirname);
foreach($dir as $i => $filename)
{
if($filename == '.' || $filename == '..')
continue;
var_dump($filename);
}
Example using DirectoryIterator
class
$dirname = getcwd();
$dir = new DirectoryIterator($dirname);
foreach ($dir as $path => $splFileInfo)
{
if ($splFileInfo->isDir())
continue;
// do what you have to do with your files
//example: get filename
var_dump($splFileInfo->getFilename());
}
Here is less common example using RecursiveDirectoryIterator
class:
//use current working directory, can be changed to directory of your choice
$dirname = getcwd();
$splDirectoryIterator = new RecursiveDirectoryIterator($dirname);
$splIterator = new RecursiveIteratorIterator(
$splDirectoryIterator, RecursiveIteratorIterator::SELF_FIRST
);
foreach ($splIterator as $path => $splFileInfo)
{
if ($splFileInfo->isDir())
continue;
// do what you have to do with your files
//example: get filename
var_dump($splFileInfo->getFilename());
}
Getting array of filenames in a directory which contains substring in their name
You can use scandir
method to get all file names. then iterate through it and find matches
$dir = public_path('files/MyDir');
$files = scandir ($dir);
$match = "Hello";
$match_files = array();
foreach ($files as $file) {
if((stripos($file, $match) !== false)
$match_files[]=$file;
}
print_r($match_files);
How to get the file name under a folder?
You can use the glob() function:
Example 01:
<?php
// read all files inside the given directory
// limited to a specific file extension
$files = glob("./ABC/*.txt");
?>
Example 02:
<?php
// perform actions for each file found
foreach (glob("./ABC/*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
Example 03: Using RecursiveIteratorIterator
<?php
foreach(new RecursiveIteratorIterator( new RecursiveDirectoryIterator("../")) as $file) {
if (strtolower(substr($file, -4)) == ".txt") {
echo $file;
}
}
?>
Related Topics
What's the Difference Between Isset() and Array_Key_Exists()
How to Perform Static Code Analysis in PHP
Run Process With Realtime Output in PHP
Remove New Lines from String and Replace With One Empty Space
Laravel: Syntax Error or Access Violation: 1055 Error
How to Test a Url For 404 in PHP
Best Solution to Protect PHP Code Without Encryption
Using an Array as Needles in Strpos
What Are the Differences in Die() and Exit() in PHP
Are Arrays in PHP Copied as Value or as Reference to New Variables, and When Passed to Functions
PHP Sort Array by Subarray Value
How to Set Http Header to Utf-8 Using PHP Which Is Valid in W3C Validator
Bulk Insertion in Laravel Using Eloquent Orm
PHP Multidimensional Array Searching (Find Key by Specific Value)