Appearance
How to list files and folder in a dir (PHP)
In PHP, you can use the scandir() function to list the files and directories in a directory. This function returns an array of file and directory names.
Here's an example:
Example: Using scandir()
php
<?php
// Define the directory path
$dir = '/path/to/directory';
// Check if the directory exists and is readable
if (!is_dir($dir)) {
echo "Directory does not exist.";
exit;
}
// Get an array of the directory contents using scandir()
$files = scandir($dir);
// Output the contents of the directory using print_r()
echo "Directory contents: \n";
print_r($files);
?>Note: scandir() includes . and .. entries in the returned array. You can filter them out using array_diff() if needed.
You can also use the glob() function to list files and folders in a directory.
Example: Using glob()
php
<?php
// Get an array of all files in the directory using glob()
$files = glob('/path/to/directory/*');
// Loop through the array of files
foreach ($files as $file) {
// Output each full path on a new line
echo $file . "\n";
}
?>This will print the full paths of all files and directories in the specified directory, one per line.
You can also pass a second parameter to glob() to filter the type of files you want to retrieve.
Example: Filtering files with glob()
php
<?php
// Get an array of all .txt files in the directory using glob()
$files = glob('/path/to/directory/*.txt');
// Loop through the array of files
foreach ($files as $file) {
// Output each full path on a new line
echo $file . "\n";
}
?>This will print the full paths of all .txt files in the specified directory, one per line.