-2

In a recent HTML project, I'm trying to make a 's background-image change everytime the page is loaded, using PHP. I know both CSS and HTML, but not PHP.

As I'm a newbie with PHP, I decided to search how to select a random image inside a folder using PHP and I used the solution to this question from StackOverflow.

The PHP code seems to work, as the page doesn't throw any errors. The image is not being displayed as the background of the div (not image is being displayed).

Here's the piece of code:

    <?php
        $directory = "/images/headerBg/";
        $filecount = 0;
        $files = glob($directory . "*");

        if ($files){
            $filecount = count($files);
        }

        $IMG = mt_rand(1, $filecount);
    ?>

    <style type="text/css">
        .bgImg {
            background-image: url("/images/headerBg/<?php echo $IMG ?>.jpg");
        }
    </style>

    <div class="bgImg">
        <!-- The div with the changing background -->
    </div> 

Note 1: Files are named 0.jpg to the last one (n.jpg).

Note 2: I can't use arrays, as I'll add more photos on the way.

spund3
  • 127
  • 6

2 Answers2

2

You're trying to show the random index of the file you generated and not the file itself. Your code would only work if the filenames in the directory you search for are all the format of 1.jpg, 2.jpg, etc...

Change

background-image; url("/images/headerBg/<?php echo $IMG ?>.jpg");

to

background-image: url("/images/headerBg/<?php echo $files[$IMG] ?>");
Lance Whatley
  • 2,395
  • 1
  • 13
  • 16
  • I'm using numbers for each image, still doesn't working. I used your code and nothing happens. – spund3 Sep 17 '17 at 21:15
0

You can do that with glob but if you need some performance it's not a really good idea to read a whole directory every time your page is loaded.

So in your case i would prefer an array with your file names. And pick randomly an image from your array.

$myBgImageArray = [
    0 => '123123.jpg',
    1 => '212312.jpg',
] 

<style type="text/css">
    .bgImg {
        background-image; url("/images/headerBg/<?php echo $myBgImageArray[mt_rand(0, count($myBgImageArray) - 1)]; ?>");
    }
</style>

something like this. For security reasons it's better to define names and other things in a static way. Don't use filename that can be manipulated or where user can put images with cruel names or spaces. That can break your page and cause errors.

René Höhle
  • 26,716
  • 22
  • 73
  • 82