Wanted to do a random change of background image function, written in JavaScript, the program flow should be: Create a picture array-> randomly select one of the values in the array-> generate style and write the body tag.
But with JS do, have the following disadvantages:
1. If the browser disables JS, it will fail, and write code is to consider compatibility.
2. Maintenance is more troublesome, the location of the pictures are stored in the array.
So I proposed to use PHP processing, but I and her php are half a bucket of water, for a while also can not think how to do. Today's high, see a PHP random display directory under the image of the source code, learn, and share.
First look at the principle: Get a list of files from a directory (commonly used on the web is jpg/gif/png)-> Select a picture-> output code by random function.
The PHP code is as follows:
Copy Code code as follows:
$imglist = ';
Save the picture's directory with the $img_folder variable, you must end with "/"
$img _folder = "images/tutorials/";
Mt_srand (Double) microtime () *1000);
Working with directory classes
$imgs = Dir ($img _folder);
Check to see if there are any pictures in the directory and generate a list
while ($file = $imgs->read ()) {
if (eregi ("gif", $file) | | eregi ("JPG", $file) | | eregi ("PNG", $file)
$imglist. = "$file";
} closedir ($imgs->handle);
Put the items in the list into an array
$imglist = Explode ("", $imglist);
$no = sizeof ($imglist)-2;
Generates a random number between 0 and the number of pictures
$random = Mt_rand (0, $no);
$image = $imglist [$random];
Output results
Echo '
If you want to change the page background through this function, you can change the last sentence to read:
Copy Code code as follows:
Echo ' <body style= background-image: '. $img _folder. $image. ' > ';</body>
Replace <body> label with whole program.
If you need to call this program multiple times, you can write a function that you rewrite as needed.
Summarize
The benefits of using PHP to output random pictures are:
1. Maintenance is simple, only need to control the number of pictures in the directory.
2. You can customize the file type, as long as you need to change to a random output of a flash also line
3. You can customize the output, in other words, use it wherever you want.
4. Function more powerful when rewritten as a function