Home » PHP

Get the contents of a directory in PHP

In this article, we will 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

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?

Code - PHP

<?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);  
        }  
    }  
}
?>

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.