Q:

Get the contents of a directory in PHP

belongs to collection: PHP Miscellaneous

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP Miscellaneous

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Setting Cookies in PHP... >>
<< Display source code of the website with PHP...