Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does "." (dot) come from when using PHP ´scandir´

Tags:

php

scandir

I'm a bit confused.
I'm building a PHP function to loop out images in a specified dir.

PHP

$dir = "bilder/".$objekt[0]['objekt_nr']."/thumbnail/";
$thumbnails = scandir($dir);

print_r($thumbnails);

foreach ($thumbnails as $value) {
   echo "<img src='".$dir.$value. "'>";
}

array

(
[0] => .
[1] => ..
[2] => bjornc.jpg
[3] => test_bild3.jpg
)

HTML

<img src='bilder/22159/thumbnail/.'>
<img src='bilder/22159/thumbnail/..'>
<img src='bilder/22159/thumbnail/bjornc.jpg'>
<img src='bilder/22159/thumbnail/test_bild3.jpg'>

How can i get rid of theese dots?
I guess it´s the directorie dots..

UPDATE

The most easy way was found in php.net manual

$thumbnails = array_diff(scandir($dir), array('..', '.'));
like image 305
Björn C Avatar asked Jul 22 '26 02:07

Björn C


2 Answers

The dot directory is the current directory. Dot-dot is the parent directory.

If you want to create a list of files in a directory you should really skip those two, or really any directory starting with a leading dot (on POSIX systems like Linux and OSX those are supposed to be hidden directories).

You can do that by simply check if the first character in the file name is a dot, and if it is just skip it (i.e. you continue the loop).

like image 172
Some programmer dude Avatar answered Jul 23 '26 14:07

Some programmer dude


You can skip it by using in_array as

foreach ($thumbnails as $value) {
    if (!in_array($value, array(".", ".."))) {
        echo "<img src='" . $dir . $value . "'>";
    }
}
like image 22
Saty Avatar answered Jul 23 '26 16:07

Saty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!