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

旧街凉风 提交于 2021-02-19 05:54:20

问题


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('..', '.'));

回答1:


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).




回答2:


You can skip it by using in_array as

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



回答3:


You can also use this

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



回答4:


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);



回答5:


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);
        }
    }
    ?>



回答6:


@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'/>";
}


来源:https://stackoverflow.com/questions/36149598/where-does-dot-come-from-when-using-php-%c2%b4scandir%c2%b4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!