"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to List File Names in a Directory Using PHP?

How to List File Names in a Directory Using PHP?

Published on 2024-11-12
Browse:248

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:

foreach (new DirectoryIterator('.') as $file) {
    if($file->isDot()) continue;
    print $file->getFilename() . '
'; }

scandir:

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

$files = scandir('.');
foreach($files as $file) {
    if($file == '.' || $file == '..') continue;
    print $file . '
'; }

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:

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if($file == '.' || $file == '..') continue;
        print $file . '
'; } closedir($handle); }

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:

foreach (glob("*") as $file) {
    if($file == '.' || $file == '..') continue;
    print $file . '
'; }

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

Release Statement This article is reprinted at: 1729247958 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3