2011-08-06 15 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