How to Fetch File Names Within a Directory in PHP

Patricia Arquette
Release: 2024-10-18 18:42:03
Original
119 people have browsed it

How to Fetch File Names Within a Directory in PHP

Fetching File Names Within a Directory in PHP

In PHP, acquiring the file names within a directory requires specific commands. Having exhausted search engines, this question explores the various methods available for this task.

Approaches

1. DirectoryIterator (Recommended)

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

2. scandir

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

3. opendir and readdir

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

4. glob

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

Additional Note on glob

Glob offers a unique advantage over other methods. The asterisk (*) wildcard can be used for matching files based on criteria. For instance, glob('*.txt') retrieves all text files in the directory, while glob('image_*') fetches files starting with "image_".

The above is the detailed content of How to Fetch File Names Within a Directory in 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!