PHP random file include error

Discussion in 'PHP' started by aluke, Dec 28, 2007.

  1. #1
    In my proxy page is a code:
    
    <? 
    $path = '/home/aluke/public_html/ads/'; // remeber trailing slash!
    $handle = opendir ($path);
    while (($filename = readdir ($handle)) !== false)
    {
    if ($filename != '.' && $filename != '..')
    {
    $file_array[] = $filename;
    }
    }
    
    $rand = rand (0, count ($file_array));
    include ($path . $file_array[$rand]);  
    ?>
    
    PHP:
    This code includes random file from ads folder.
    Problem is that it sometimes gives me the following error:
    Warning: main(/home/aluke/public_html/ads/) [function.main]: failed to open stream: Success in /home/aluke/public_html/index.php on line 125
    
    Warning: main(/home/aluke/public_html/ads/) [function.main]: failed to open stream: Permission denied in /home/aluke/public_html/index.php on line 125
    
    Warning: main() [function.include]: Failed opening '/home/aluke/public_html/ads/' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/aluke/public_html/index.php on line 125
    PHP:
    What causes this error?
    Thanks in advance!
     
    aluke, Dec 28, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    The range is wrong.

    Between 0 and the "sizeof" your array is wrong, because if rand() decides to take the value returned by sizeof() (The highest value of the allowed range), you'll get an undefined index.

    Use array_rand() instead, to avoid complications.

    
    $rand = $file_array[array_rand($file_array)];
    
    PHP:
     
    nico_swd, Dec 28, 2007 IP
  3. aluke

    aluke Well-Known Member

    Messages:
    170
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    130
    #3
    I replaced
    $rand = rand (0, count ($file_array));
    PHP:
    with
    $rand = $file_array[array_rand($file_array)];
    PHP:
    but now it gives me that error all the time...
     
    aluke, Dec 28, 2007 IP
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    Take out the $file_array[$rand] in your include:
    
    include ($path . $file_array[$rand]);  
    
    PHP:
    And replace it with $rand.
    
    include $path . $rand;
    
    PHP:
    EDIT:

    Or leave your code as it is, and just replace:
    
    $rand = $file_array[array_rand($file_array)];
    
    PHP:
    With
    
    $rand = array_rand($file_array);
    
    PHP:
     
    nico_swd, Dec 28, 2007 IP
  5. aluke

    aluke Well-Known Member

    Messages:
    170
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    130
    #5
    Tried this, it works perfectly now. Thank you very much!
     
    aluke, Dec 28, 2007 IP
    super likes this.