Skip to content
Advertisement

php Setting background image randomly from folder

I am trying to randomly set the background image of a webpage from a folder via PHP.

I have the following code:

JavaScript

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:

JavaScript

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

JavaScript

This is a complete example which uses glob to fetch the images in the folder

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement