0

I'm uning a php script to get a random news article from a directory and to display it on my website, this works fine, however when I try to recreate it to show something else at random, the new one doesn't work - Here is my code:

<?php
function random_unit($unit_dir = 'sections/units')
{
    $units = glob($unit_dir . '/*.php');
    $unit = array_rand($units);
    return $units[$unit];
}
$unit_1 = random_unit("sections/units");
?>
<?php $unit_1 = file_get_contents( $unit_1 ); ?>
<?php echo $unit_1; ?> // Echo's The Contents Of Selected Random File

Can anyone see where I might have gone wrong?

user3177012
  • 663
  • 2
  • 8
  • 19
  • "Doesn't work" - What are you expecting? What is happening instead? Have you turned on [error reporting](http://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php)? What files are in your directory? Have you tried prefixing `dirname(__FILE__)`, as in `$unit_dir = dirname(__FILE__) . '/sections/units'`? – wavemode Sep 16 '14 at 12:35
  • I'm expecting the contents of the random file to show up where `echo $unit_1` exists but nothing is happening - No errors or anything! – user3177012 Sep 16 '14 at 13:54
  • It sounds like `file_get_contents` is returning false, which is why I'm curious as to what files are in the path, as well as the contents of `$unit` after your code runs. – wavemode Sep 16 '14 at 15:50
  • The only file inside the directory path is `A.php` - The content of `$unit` is nothing I guess – user3177012 Sep 16 '14 at 16:00
  • Why aren't you calling `random_unit()` in your code? You are just using the variable `$unit` by itself. Did you mean to write `file_get_contents( random_unit() )`? – wavemode Sep 16 '14 at 16:05
  • Had another look and it looks like I was missing `$unit_1 = random_unit("sections/units");` form the first php block – user3177012 Sep 16 '14 at 16:11

0 Answers0