PHP Scandir returns extra periods

匿名 (未验证) 提交于 2019-12-03 02:28:01

问题:

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/img/bg/"; $dh  = opendir($dir); while (false !== ($filename = readdir($dh))) {     $files[] = $filename; }  $random_key = array_rand($files, 1);  $random = $files[$random_key]; 

Then I am just using some simple jquery to attach the images as backgrounds:

<script> $(document).ready(function(){      $("body").css( "background" , "url(http://'.$url_root.'/views/img/bg/'.$random.'), center center" );  }); </script> 

Everything works fine but the array of all the images in the background folder seems to be returning stuff like '.' or '..' instead of image names every once in a while. Im not sure what is going on - any ideas?

回答1:

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

while (false !== ($filename = readdir($dh))) {     if ($filename != '.' && $filename != '..')             $files[] = $filename; } 


回答2:

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.



回答3:

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


回答4:

$dh = opendir("c:\"); while (false !== ($filename = readdir($dh))) {     if ($filename != '.' && $filename != '..')            $files[] = $filename; } 


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