Home  >  Article  >  Backend Development  >  PHP code to get pictures in a directory and display them randomly_PHP tutorial

PHP code to get pictures in a directory and display them randomly_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:42:03841browse

At that time, I 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.
But 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 troublesome, as the positions of pictures are stored in arrays.
So I suggested using PHP to deal with it, but she and I were both half-experienced in PHP and 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.

Let’s take a look at the principle first: Get a list of files of a certain type from a directory (usually jpg/gif/png if used on the WEB) -> Select an image through a random function -> Output the code.
The PHP code is as follows:

Copy code The code is as follows:

$imglist='';
// Use the $img_folder variable to save the directory where the image is located, which must end with "/"
$img_folder = "images/tutorials/";
mt_srand((double)microtime()*1000);
//Use directory Class
$imgs = dir($img_folder);
//Check whether there are images 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 items in the list into an array
$imglist = explode(" ", $imglist);
$no = sizeof($ imglist)-2;
//Generate a random number between 0 and the number of images
$random = mt_rand(0, $no);
$image = $imglist[$random];
//Output result
echo '';

If you want to change the page background through this function, you can change the last sentence to:
Copy the code The code is as follows:

echo '

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321069.htmlTechArticleAt that time, I wanted to create a function that randomly changes the background image. If written in JavaScript, the program flow should be: Create a picture Array - randomly select one of the values ​​in the array - generate a style and write...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn