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:

<?php

// Define the directory path
$dir = '/path/to/directory';

// 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);

?>

This will print an array of all files and directories in the specified directory.

Watch a course Learn object oriented PHP

You can also use glob() function to list files and folder in a directory

<?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 file name on a new line
    echo $file . "\n";
}

?>

This will print the names of all files and directories in the specified directory, one per line.

You can also pass the second parameter in glob to filter the type of files you want to get.

<?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 file name on a new line
    echo $file . "\n";
}

?>

This will print the names of all txt files in the specified directory, one per line.