Blank array_rand() when sourcing random mp3 from directory
This is in the body of my index.php
i开发者_开发知识库n root dir of site and localhost/sound/
contains a bunch of randomly named mp3
files.
<?php
$files = glob("/sound/*.mp3");
$random = array_rand($files)
?>
<embed src="<?php echo $random ?>"
width="140" height="40" autostart="true" loop="TRUE">
</embed>
When I view source of the page in browser it shows
<embed src=""
width="140" height="40" autostart="true" loop="TRUE">
</embed>
Ensure that glob
is actually returning matches:
$files = glob("/sound/*.mp3");
if (count($files) < 1)
die('No files found');
$random = $files[array_rand($files)];
...
You could do the same thing, but provide a fallback default:
$files = glob("/sound/*.mp3");
$random = count($files) > 1 ? $files[array_rand($files)] : 'path/to/default.mp3';
...
First, make sure you are actually getting some file names back. Note that glob()
expects a path on your filesystem. The path /sound/*.mp3
should probably be something like sound/*.mp3
(i.e. relative to your PHP script) or /var/www/html/sound/*.mp3
(an absolute path to where your web files are stored).
You should put a check in your code to verify that you're getting files back. For example:
if ($files === FALSE || count($files) == 0)
{
die('No MP3s!');
}
Second, array_rand()
returns a random array key. You'll have to look up that key in the array to retrieve the corresponding value:
<embed src="<?php echo $files[$random] ?>"
精彩评论