Home >Backend Development >PHP Tutorial >How to List Directory Files in PHP using `scandir()`?

How to List Directory Files in PHP using `scandir()`?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-20 17:37:11848browse

How to List Directory Files in PHP using `scandir()`?

How to List Directory Files in PHP

Question:

How can you list all the files in a specific directory using PHP?

Answer:

The scandir() function provides a convenient way to list files in a directory. For example, the following code retrieves a list of files from the usernames directory:

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

Additional Considerations:

  • The scandir() function includes hidden files (those starting with a period) in the results. To remove hidden files, you can use the array_diff() function:
$files = array_diff(scandir($path), array('.', '..'));
  • The scandir() function sorts the results alphabetically. If you need a different sorting order, you can use the natsort() or usort() functions.

The above is the detailed content of How to List Directory Files in PHP using `scandir()`?. 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