I am trying to randomly set the background image of a webpage from a folder via PHP.
I have the following code:
<!DOCTYPE HTML> <html> <head> <link rel="stylesheet" type="text/css" href="style.css"> <title>404</title> </head> <body id="Background404"> <p>404-Page not found. <a href="http://url.com>Home.</a></p> <?php $dir = '/var/www/html/Images'; $fileNames = array(); if(is_dir($dir)){ $handle = opendir($dir); while(false !== ($file = readdir($handle))){ if(is_file($dir.'/'.$file) && is_readable($dir.'/'.$file)){ $fileNames[] = $file; } } closedir($handle); $fileNames = array_reverse($fileNames); print_r($fileNames); } $totalLength = sizeof($fileNames); $randInt = rand(0, $totalLength); $randFile = $fileNames[$randInt]; echo '<style> #Background404{background: url($randFile);}</style>'; ?> </body> </html>
Note: the printing of the files is just to ensure I reach that point in code and to see what the files are called. I found a similar question here: Random Background Image PHP but when I used that answer I got just a pure white background.
Here is a copy of printed array:
Array ( [0] => GraniteBridge.png [1] => mobileBackground.png [2] => OtherKingdom.png [3] => NetherBase.png [4] => BackgroundTablet.png [5] => Snowy.png [6] => Village.png [7] => background2.png [8] => CactusFarm.png [9] => FrontView.png [10] => CreditsPortal.png [11] => FrontNight.png [12] => background4.png [13] => XPFarmRailway.png [14] => GoldIronFarms.png [15] => Pyramid.png [16] => NetherFortress.png [17] => TheEnd.png [18] => Library.png [19] => Background.png [20] => twitter.png [21] => mobileBackground1.png [22] => mobileBackground2.png [23] => BirdsEyeView.png [24] => EndPortal.png [25] => AboveVillage.png [26] => TowerToTheHeavens.png [27] => TowerArmorStands.png [28] => FullSizeBackground.png [29] => Mansion.png [30] => Night.png [31] => Dojo.png )
Advertisement
Answer
You can use array_rand to get a random index in the array. Then you can use that random index to get an image from your array
$randomImage = $images[array_rand($images)];
This is a complete example which uses glob to fetch the images in the folder
<?php $imagesDir = '/var/www/html/images'; $images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE); $randomImage = $images[array_rand($images)]; ?> <img style="background-image:url('/path/to/images/<?php echo $randomImage ?>');"/>