2011-08-06 43 views
0

我有這個php代碼,應該把所有的php文件放在一個比x天更新的目錄下,並且隨機選擇其中一個包含它們。代碼工作完全符合這部分遺漏了:
& & filectime($路徑$文件。)>時間() - 60 * 60 * 24 * 4PHP「隨機包含」代碼不按預期工作

當我在代碼的那部分它給了我這2個錯誤,但只有當NONE的文件符合要求時纔會這樣。如果至少一個文件符合質量要求它的功能normaly:

Warning: include() [function.include]: Filename cannot be empty in FILEPATH/THISFILE.php on line 15 


Warning: include() [function.include]: Failed opening '' for inclusion (include_path='.:/usr/local/lib/php-5.2.17/lib/php') in FILEPATH/THISFILE.php on line 15 

我不知道爲什麼這樣一個「條件」創造了這個問題。如果沒有文件滿足條件沒有「時間如果」它仍然正常工作。
有誰知道發生了什麼事?謝謝,呂克
這裏是第15行的代碼標記:

<?php 
$files = array(); 
$path = "nasa-news/"; 
if($handle = opendir($path)) 
{  while (false !== ($file = readdir($handle))) 
    {    if($file != "." && $file != ".." && !is_dir($path.$file) && strpos($file, '.php',1) && filectime($path.$file) > time()-60*60*24*4) // Only if it is a .php file that is less than 4 days old. 
    {         $files[] = $path.$file;         
    }     
}   
// You need to populate the $files variable before you count it;)   
$file = $files[ rand(0, count($files)-1) ];   
// Now we can include it!   
include ("$file"); 
} 
else 
{   
print "<br />No New News Found!"; // If no files meet the conditions this should print. 
LINE 15 }  
?> 

回答

2

的問題是這一行:

$file = $files[ rand(0, count($files)-1) ]; 

當你的數組沒有任何元素,這將導致一個未定義的索引。因此,$file是空的...

所以你需要檢查你的數組是否爲空。 順便說一句,你可以嘗試洗牌數組,並採取第一個元素。簡單得多:

if (count($files)) 
{ 
    shuffle($files); 
    $file = $files[0]; // your random element, have some fun with it! 
} 
else 
{ 
    // Handle edge case 
} 
+0

哎呦。固定的功能名稱。 – Franz

+0

現在,這是一個真正的答案。 – Franz

+0

謝謝,你的幫助幫助了我!這是使用洗牌而不是隨機的好主意。這是我第一次使用堆棧溢出......而且我對它有很好的體驗。 – MindMaster