简体   繁体   中英

Where does "." (dot) come from when using 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('..', '.'));

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 (ie you continue the loop).

You can skip it by using in_array as

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

they are directory and parent directory, they can be removed with following code:

    <?php
    $dir = "downloads/";
    if (is_dir($dir)){
        if ($dir_handler = opendir($dir)){
            while (($file = readdir($dir_handler)) !== false){
                if ($file!="."&&$file!="..") {
                    //your code
                }
            }
        closedir($dir_handler);
        }
    }
    ?>

You can also use this

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

If you are looking for a specific file type, such as images, you are better off using glob .
It allows you to pass a pattern of extensions.
This way you can be sure you fetch only the files you are looking for.

Example for multiple file types, .jpg and .png

$dir = "bilder/".$objekt[0]['objekt_nr']."/thumbnail/";
$files = glob("*.{jpg,png}", GLOB_BRACE);

print_r($files);

GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'

Example for a single file type, .jpg

$dir = "bilder/".$objekt[0]['objekt_nr']."/thumbnail/";
$files = glob("*.jpg");

print_r($files);

@joachim Pileborg answer is correct, By the way you can also use glob()

$thumbnails = glob("$dir/*.jpg");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM