Liam Fell
Liam Fell

Reputation: 1320

PHP: Using scandir bu excluding ../ ./ in the result

I'm using scandir and a foreach loop to display a list of files in a directory to the user. My code is below:

        $dir = scandir('/user1/caravans/public_html/wordpress/wp-content/uploads/wpallimport/files');

        foreach($dir as $directory)
{
        echo "<br/><input type='checkbox' name=\"File[]\" value='$directory'/>$directory<br>";
        }

The problem is the script also echos a "." and a ".." (without the speech marks), is there an elegant way to remove these? Short or a regular expression. Thanks

Upvotes: 2

Views: 409

Answers (3)

swidmann
swidmann

Reputation: 2792

Just continue if the directory is . or .. I recommend to take a look at the control structures here

$dir = scandir('/user1/caravans/public_html/wordpress/wp-content/uploads/wpallimport/files');

foreach($dir as $directory) {
    if( $directory == '.' || $directory == '..' ) {
        // directory is . or ..
        // continue will directly move on with the next value in $directory
        continue;
    }

    echo "<br/><input type='checkbox' name=\"File[]\" value='$directory'/>$directory<br>";
}

Instead of this:

if( $directory == '.' || $directory == '..' ) {
    // directory is . or ..
    // continue will directly move on with the next value in $directory
    continue;
}

you can use a short version of it:

if( $directory == '.' || $directory == '..' ) continue;

Upvotes: 6

madsen
madsen

Reputation: 462

Another solution, in addition to swidmann's answer, is to simply remove '.' and '..' before iterating over them.

Adapted from http://php.net/manual/en/function.scandir.php#107215

$path    = '/user1/caravans/public_html/wordpress/wp-content/uploads/wpallimport/files';
$exclude = ['.', '..'];
$dir     = array_diff(scandir($path), $exclude);

foreach ($dir as $directory) {
    // ...
}

That way you can also easily add other directories and files to the excluded list should the need arise in the future.

Upvotes: 1

user594138
user594138

Reputation:

You can eliminate these directories with array_diff:

$dir = scandir($path);
$dir = array_diff($dir, array('.', '..'));
foreach($dir as $entry) {
    // ...
}

Upvotes: 2

Related Questions