PHP Scandir returns extra periods

前端 未结 4 1743
别跟我提以往
别跟我提以往 2021-01-15 07:27

So I am trying to build a script that scans a directory and returns random images to be used as backgrounds.

The php looks like this:

$dir = \"views         


        
相关标签:
4条回答
  • 2021-01-15 08:17

    Use glob() so you can filter the files.

    $files = glob('views/img/bg/*.jpg');
    $random = $files[array_rand($files)];
    

    Since you're specifying *.jpg, $files contains only JPG files and you don't need to remove the . and .. items.

    0 讨论(0)
  • 2021-01-15 08:22
    $dh = opendir("c:\");
    while (false !== ($filename = readdir($dh))) {
        if ($filename != '.' && $filename != '..')    
           $files[] = $filename;
    }
    
    0 讨论(0)
  • 2021-01-15 08:25

    Why not use regex? That way it captures any amount of periods. (i.e. ".", "..", "..." etc..)

    while (false !== ($filename = readdir($dh))) {
            if(!preg_match('/^\.*$/',$filename)){
                $files[] = $filename;
            }
    
    0 讨论(0)
  • 2021-01-15 08:31

    '.' and '..' are returned for current and parent directory. You can filter them:

    while (false !== ($filename = readdir($dh))) {
        if ($filename != '.' && $filename != '..')    
            $files[] = $filename;
    }
    
    0 讨论(0)
提交回复
热议问题