PHP Random Background Image from a directory

<?php function get_rand_img($dir) { $arr = array(); $list = scandir($dir); foreach ($list as $file) { if (!isset($img)) { $img = ''; } if (is_file($dir . '/' . $file)) { $ext = end(explode('.', $file)); if ($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png' || $ext == 'GIF' || $ext == 'JPEG' || $ext == 'JPG' || $ext == 'PNG') { array_push($arr, $file); $img = $file; } } } if ($img != '') { $img = array_rand($arr); $img = $arr[$img]; } $img = str_replace("'", "\'", $img); $img = str_replace(" ", "%20", $img); return $img; } ?> <div class='hero-banner-img' style='background-image: url(/banners/<?php echo get_rand_img('banners'); ?>)'></div>

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.