At that time, I wanted to create a function that randomly changes background images. 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 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 more 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 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.
Let’s first 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.
The PHP code is as follows:
$imglist=''; //用$img_folder变量保存图片所在目录,必须用“/”结尾 $img_folder = "images/tutorials/"; mt_srand((double)microtime()*1000); //使用目录类 $imgs = dir($img_folder); //检查目录下是否有图片,并生成一个清单 while ($file = $imgs->read()) { if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file)) $imglist .= "$file "; } closedir($imgs->handle); //把清单里的项都放到一个数组里 $imglist = explode(" ", $imglist); $no = sizeof($imglist)-2; //生成一个介于0和图片数量之间的随机数 $random = mt_rand(0, $no); $image = $imglist[$random]; //输出结果 echo '<img src="'.$img_folder.$image.'" border="0/" alt="" />';
If you want to change the page background through this function, you can change the last sentence to:
The code is as follows:
echo '<body style="background-image:'.$img_folder.$image.'>';</body>
And replace the
tag 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 benefits 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 results. In other words, you can use it anywhere.
4. Rewrite The function becomes more powerful after being converted into a function
The above introduces the code for displaying the satellite cloud image released by the meteorological observatory in PHP to obtain the pictures in the directory and display them randomly, including the content of displaying the satellite cloud image released by the meteorological observatory. I hope you are interested in the PHP tutorial Friends help.