There are two methods to build a random image API in PHP:
- Local random images
- External random images
Next, let's briefly explain how to write them.
Text Tutorial#
Local Random Images#
First, create a folder named "photos" and a file named "index.php". Then, put the images in the "photos" folder and write the following code in the "index.php" file.
<?php
$img_array = glob("photos/*.{gif,jpg,png}",GLOB_BRACE);
$img = array_rand($img_array);
$dz = $img_array[$img];
header("Location:".$dz);
?>
Save it. You can randomly call the images in the "img" folder through the API. Finally, access the URL: http://domain.
External Random Images#
First, create "photos.txt" and "index.php" files. Then, put the external image links (one per line) in the "photos.txt" document. Add the following code to the "index.php" file.
<?php
$arr=file('photos.txt');
$n=count($arr)-1;
for ($i=1;$i<=1;$i++){
$x=rand(0,$n);header("Location:".$arr[$x],"\n");}
?>
Finally, access the URL: http://domain! In "photos.txt", you can fill in external image links like those from Sina or your own image hosting service. It is fast, stable, and does not consume memory.
API Testing#
I used the second method to obtain external image links from my own image hosting service.
https://img.yct.ee
How to Use#
If you don't want to build it yourself, you can directly use mine.
<img src="https://img.yct.ee">