Php scandir() problems

Aiden Ryan picture Aiden Ryan · Aug 10, 2011 · Viewed 14.1k times · Source

I was wondering, my Scandir() function works on a php $_GET variable, so the variable returns the folder, but I'm having a problem because I'm not sure how to echo out an error if there is a problem with with directory.

this is the error I am getting:

Warning: scandir(users/ro/f) [function.scandir]: failed to open dir: No such file or directory in C:\xampp\htdocs\OSO\desktop\main_content\file.php on line 31

This is my code

$folder = $_GET['file_folder'];
$directory = "users/$username/$folder";
if (scandir($directory, 0)) {
    unset($documents[0], $documents[1]);
    $documents = scandir($directory, 0);

    // for each loop
} else {
    echo "No such directory";
}

Cheers in advance

Answer

Veger picture Veger · Aug 11, 2011

I would first check whether $directory exists using is_dir() before calling scandir():

if (is_dir($directory)) {
    $filenames = scandir($directory, 0);
    // do something
} else {
    echo "No such directory";
}