Search code examples
phprandomdirectorymp3

Blank array_rand() when sourcing random mp3 from directory


This is in the body of my index.php in 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>

Solution

  • 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';
    
    ...