I have this php code that should take all the php files in a directory that are newer than x days and have one of them chosen randomly for inclusion. The code works perfectly with this part left out:
&& filectime( $path.$file ) > time()-60*60*24*4When I do have that part in the code it gives me these 2 errors BUT ONLY if NONE of the files meet the requirments. If at least one file meets the requirments it functions 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
I am not sure why th开发者_运维百科at one "condition" is creating this problem. If no file meets the condition without the "time if" it still functions normaly.
Does anyone know what is going on? Thank, Luc Here is the code with line 15 marked:<?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 }
?>
The problem is this line:
$file = $files[ rand( 0, count( $files )-1 ) ];
When your array has no elements, this will cause an undefined index. Thus, $file
is empty...
So you need to check whether your array is empty first. Btw, you could try shuffling the array and taking the first element. Much simpler:
if (count($files))
{
shuffle($files);
$file = $files[0]; // your random element, have some fun with it!
}
else
{
// Handle edge case
}
精彩评论