Get the contents of a directory in PHP

Learn, how to get contents of a directory in PHP? It can useful to check if file is already present in the directory or the number of contents in the directory.
Submitted by Abhishek Pathak, on October 31, 2017 [Last updated : March 14, 2023]

Content of a Directory

PHP is the server side scripting language that is used to generate dynamic HTML content. While it serves this purpose very well, we can also use it to list the contents of a directory. It can useful to check if file is already present in the directory or the number of contents in the directory.

In this article, we will learn how to get contents of a directory in PHP. Following is the code?

PHP code to get the content of a directory

<?php
function list_files($dir) {  
    if(is_dir($dir)) {  
        if($handle = opendir($dir))  {  
            while(($file = readdir($handle)) !== false)  
            {  
                if($file != ".") {  
                    echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";  
                }  
            }  
            closedir($handle);  
        }  
    }  
}
?>

Code Explanation

In this code, we create a function named list_files which expects the dir as argument, which is the directory to list. Inside this function, we first check if it is directory using is_dir() method. If true, then inside we open the directory using opendir() method and assign the result to handle variable, which is used to refer to this directory.

Next, we run a while loop until there are no more files using the readdir() which reads the contents of the directory. Inside this, we simply check if file is not equal to . (period) that is used for extensions, we can print the name of the file along with it's link using $dir.$file. After the loop is over, we close the directory using closedir() method.

Hope you like the article. Share your thoughts in the comments below.

More PHP Programs »





All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.