Home >Backend Development >PHP Tutorial >Why Does My PHP Directory Listing Return '1' Instead of Filenames?

Why Does My PHP Directory Listing Return '1' Instead of Filenames?

Susan Sarandon
Susan SarandonOriginal
2024-12-05 06:39:15640browse

Why Does My PHP Directory Listing Return

Retrieving File Names from a Directory in PHP

In PHP, obtaining the names of files within a directory can be a straightforward task. However, you may encounter an issue where the code you've presented returns '1' instead of the file names.

Let's delve into the code:

if (is_dir($log_directory)) {
    if ($handle = opendir($log_directory)) {
        while($file = readdir($handle) !== FALSE) {
            $results_array[] = $file;
        }
        closedir($handle);
    }
}

In this code, you're attempting to read files from a directory using opendir() and readdir(). While this approach works in many cases, it may not always display the file names correctly.

Solution: Utilizing glob() for File Retrieval

Instead of using opendir() and readdir(), consider leveraging the glob() function. It provides a more efficient way to retrieve a list of files within a directory:

foreach(glob($log_directory.'/*.*') as $file) {
    ...
}

In this code, glob() will search the $log_directory for all files with any file extension (*.*). It returns an array containing the full paths to the found files.

By iterating over the array obtained from glob(), you can access each file's full path, including its name. This method eliminates the issue of getting '1' as the file name, providing you with the actual file names within the directory.

The above is the detailed content of Why Does My PHP Directory Listing Return '1' Instead of Filenames?. 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