Search code examples
phpfile-get-contents

Random URL File Get Content PHP


i was trying to rotate url using file get content but there's little error which I am not able to figure out.

    <?php
    //Rotate
$urls = array();
$divs[] = '/fun.jpg';
$divs[] = '/nuf.jpg';

echo file_get_contents(src="'. $divs[rand(0, count($divs)-1)] .'");

    ?>

But it's not returning any random div.


Solution

  • Well, if you just show images from same folder, as your PHP script is in, you should be able to do it like this. (did not test it)

    <?php
    header("Content-Type: image/jpg");
    
    $divs[] = 'fun.jpg';
    $divs[] = 'nuf.jpg';
    
    echo file_get_contents($divs[array_rand($divs)]);
    ?>
    

    You need to include header: Show image using file_get_contents

    And for picking random key from array you can use array_rand() function: https://www.php.net/manual/en/function.array-rand.php