Preface
Not long ago, on Twitter, @doublechou (talented girl, everyone follows her, blog) was working on a theme (now she is temporarily using iNove). At that time, she wanted to create a function that randomly changes the background image. If written in JavaScript, the program flow should be: create an image array -> randomly select one of the values in the array -> generate a style and write it into the body tag.
However, using JS has the following disadvantages:
1. If the browser disables JS, it will be ineffective, and you need to consider compatibility when writing code.
2. Maintenance is more troublesome, as the positions of pictures are stored in arrays.
So I proposed to use PHP to handle it, but she and I were both half-experienced in PHP, and we couldn’t figure out how to do it for a while. I'm lucky today. I saw a PHP source code that randomly displays images in a directory. I'll study it and share it.
Text
First let’s look at the principle: Get a list of files of a certain type from a directory (usually jpg/gif/png if used on the WEB) -> Select a picture through a random function -> Output the code.
PHP code is as follows:
Copy to ClipboardQuoted content: [www.bkjia.com] $imglist='';If you want to change the page background through this function, you can change the last sentence to:
Copy to ClipboardQuoted content: [www.bkjia.com] echo ''; And replace the label with the entire program.
If you need to call this program multiple times, you can write it as a function and you can rewrite it as needed.
Summary
The advantages of using PHP to output random pictures are:
1. Simple maintenance, you only need to control the number of pictures in the directory.
2. You can customize the file type. As long as you need it, you can change it to randomly output a Flash
3. You can customize the output result. In other words, you can use it anywhere
4. After being rewritten as a function, the function is more powerful
Reprinted from: http://blog.imbolo.com/