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
Release: 2024-11-24 07:46:11
Original
430 people have browsed it

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);
Copy after login

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>";
}
Copy after login

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('.', '..'));
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template