Home >Backend Development >PHP Tutorial >How Can I List All Files in a Directory Using PHP, and Exclude Hidden Files?

How Can I List All Files in a Directory Using PHP, and Exclude Hidden Files?

Linda Hamilton
Linda HamiltonOriginal
2024-11-24 07:46:11434browse

How Can I List All Files in a Directory Using PHP, and Exclude Hidden Files?

Listing All Files within a Directory Using PHP

To retrieve a listing of files within a specific directory, PHP provides a versatile function known as scandir. This function scans the specified directory and returns an array containing the names of all files found within.

Implementation

To list all files in a directory named "usernames/," you can utilize the following code:

$path = 'usernames/';
$files = scandir($path);

Displaying File Names as Hyperlinks

To create hyperlinks for each file name in the array, you can iterate over it using a loop:

foreach ($files as $file) {
  echo "<a href='$path/$file'>$file</a><br>";
}

Excluding Hidden Files from Results

By default, scandir also includes hidden files (files starting with a dot) in its results. To exclude these hidden files, you can use the array_diff function to remove "." and ".." from the array:

$files = array_diff(scandir($path), array('.', '..'));

The above is the detailed content of How Can I List All Files in a Directory Using PHP, and Exclude Hidden Files?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn