How to List File Names in a Directory Using PHP?

Linda Hamilton
Release: 2024-10-18 18:40:29
Original
941 people have browsed it

How to List File Names in a Directory Using PHP?

How to Obtain File Names within a Directory Using PHP

In PHP programming, retrieving the file names present within a directory can be accomplished through various methods. This article showcases several approaches for accessing and displaying the file names in the current directory.

DirectoryIterator (Recommended):

DirectoryIterator is a modernized and preferred method for iterating over directory contents. Its usage is demonstrated below:

<code class="php">foreach (new DirectoryIterator('.') as $file) {
    if($file->isDot()) continue;
    print $file->getFilename() . '<br>';
}</code>
Copy after login

scandir:

The scandir function scans the specified directory and returns an array containing the file names. Here's an example:

<code class="php">$files = scandir('.');
foreach($files as $file) {
    if($file == '.' || $file == '..') continue;
    print $file . '<br>';
}</code>
Copy after login

opendir and readdir:

This approach involves opening the directory using opendir and then iterating through the files using readdir. Here's how it's done:

<code class="php">if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if($file == '.' || $file == '..') continue;
        print $file . '<br>';
    }
    closedir($handle);
}</code>
Copy after login

glob:

glob is a pattern-matching function that can be used to retrieve files matching a specified pattern. Here's how it can be utilized:

<code class="php">foreach (glob("*") as $file) {
    if($file == '.' || $file == '..') continue;
    print $file . '<br>';
}</code>
Copy after login

The glob function allows for more flexibility in specifying file patterns, making it suitable for specific file name matching needs.

The above is the detailed content of How to List File Names in a Directory Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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