2015-02-10 94 views
0

我必須從PHP目錄中隨機選擇一個文件,假設有三個文件,比如index.php,a.php和b.php。我如何確保我沒有選擇index.php文件,但隨機挑選其他文件。 我有下面的代碼到這一點如何從目錄中隨機選擇一個文件?

$dir = 'uploads'; 
$files = glob($dir . '/*.php'); 
$file = array_rand($files); 
echo $files[$file]; 
+0

......由於不必在目錄的index.php保存隨機文件,不應該給回的index.php ..當然? – 2015-02-10 16:08:49

+0

添加一個if以檢查$ files [$ file]是否不等於_index.php_ – Phate01 2015-02-10 16:09:40

+0

我不能移動index.php – Asain 2015-02-10 16:09:59

回答

0

只是建立一個數組來排除和使用array_diff()

$exclude = array("$dir/index.php"); 
$files = array_diff(glob("$dir/*.php"), $exclude); 
0

這應做到:

$dir = 'uploads'; 
$files = glob($dir . '/*.php'); 
while (in_array($file = array_rand($files),array('index.php'))); 
echo $files[$file]; 

您可以在陣列方含「的index.php」在排除其他文件名。

它只在目錄中有比'index.php'更多的文件時才起作用。

0

我的設置獲取隨機文件,也許你只需要添加文件擴展名,..但這是肯定的。

我不喜歡array_rand,因爲它會複製數組,它也使用了很多CPU和RAM。

我想出了這個結果。

<?php 
$handle = opendir('yourdirname'); 
$entries = []; 
while (false !== ($entry = readdir($handle))) { 
    if($entry == 'index.php'){ 
    // Sorry now allowed to read this one... 
    }else{ 
    $entries[] = $entry; 
    } 
} 

// Echo a random item from our items in our folder. 
echo getrandomelement($entries); 


// Not using array_rand because to much CPU power got used. 
function getrandomelement($array) { 
    $pos=rand(0,sizeof($array)-1); 
     $res=$array[$pos]; 
     if (is_array($res)) return getrandomelement($res); 
     else return $res; 
} 
相關問題