Satellite imagery published by the Meteorological Observatory shows the code that PHP obtains in the directory and randomly displays the image

Source: Internet
Author: User
When I wanted to do a random replacement of the background image, written in JavaScript, the program flow should be: Create an array of images, a random selection of one of the values, create a style and write to the body tag.
But with JS do, there are the following shortcomings:
1. In case the browser disables JS, it will expire, and write code is to consider compatibility.
2. Maintenance is troublesome, the location of the picture is stored in the array.
So I proposed to use PHP processing, but I and her php are half a bucket of water, I can not think of how to do. Today, a high fortune, see a PHP random display directory of the source code, learn about, and share it.
Take a look at the principle: Get a list of files of a certain type from a directory (usually jpg/gif/png on the web), select an image---Output code by random function.
The PHP code is as follows:

Copy the Code code as follows:


$imglist = ";
Use the $img_folder variable to save the directory where the picture is located, must end with "/"
$img _folder = "images/tutorials/";
Mt_srand (Double) microtime () *1000);
Working with catalog classes
$imgs = Dir ($img _folder);
Check if there is a picture 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 all the items in the list in 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 the Code code as follows:


Echo ' 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.