Prajila V P
Prajila V P

Reputation: 5337

How can i list files in a directory using php

How can i list all files in a directory . I want only the files in root directory.If there is any directory inside the root directory i want to skip those directories and files in them.
Now am using this code

 $folderPath  = file_directory_path().'/lexalytics/';
    if ($handle = opendir($folderPath)) {
        $result .=  '<div><ul>';
        while (false !== ($entry = readdir($handle))) {
            if ($entry != "." && $entry != "..") {
                $result .=  "<li><a href=../".$folderPath.$entry.">".$entry."</a>\n</li>";
            }
        }
        $result .= '</ul></div>';
        closedir($handle);
    }

But it lists subdirectories and files in them. how can avoid those? Pls help me

Upvotes: 0

Views: 2337

Answers (3)

Flukey
Flukey

Reputation: 6555

Please use PHP5s new DirectoryIterator class:

This will only list files and exclude folders:

$directory  = file_directory_path().'/lexalytics/';
$filenames = array();
$iterator = new DirectoryIterator($directory);
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        $filenames[$fileinfo->getMTime()] = $fileinfo->getFilename();
    }
}

Upvotes: 3

user840298
user840298

Reputation:

Try this code

$folderPath  = file_directory_path().'/lexalytics/';
    $handle = @opendir($folderPath) or die("Unable to open $path");
    $result .=  '<div><ul>';
    // Loop through the files
    while ($entry = @readdir($handle)) {
        if(is_file($folderPath.$entry)) {
           $result .= "<li><a href=../".$folderPath.$entry.">".$entry."</a>\n</li>";
        }
    }
    $result .= '</ul></div>';
    closedir($handle);

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

$path = "your-path";

    // Open the folder
    $dir_handle = @opendir($path) or die("Unable to open $path");

    // Loop through the files
    while ($file = readdir($dir_handle)) {

    if($file == "." || $file == ".." || $file == "index.php" )

        continue;
        echo "<a href=\"$file\">$file</a><br />";

    }
    // Close
    closedir($dir_handle); 

Upvotes: 1

Related Questions