前言
大家好 本教程会分享两种方法搭建自己的API随机图片 今天无意中看到困困鱼博客有这个教程但是困困鱼分享的教程是图片从本地调用的 服务器配置不高的兄弟们吃服务器带宽 今天分享两种随机API图片教程
原地址:困困鱼
第一种(服务器本地调用图片)
1.新建一个文件夹,命名为:img(这个文件夹放你需要调用的图片)
2.新建一个index.php文件,写入以下代码 (这个文件就是API地址)
<?php
$img_array = glob("img/*.{webp,gif,jpg,png}",GLOB_BRACE);
$img = array_rand($img_array);
$dz = $img_array[$img];
header("Location:".$dz);
?>
第二种(服务器文件内图片链接进行调用)
1.创建一个img.txt文件 (文件内放置你的图片链接注意:一行一个链接)
2.新建一个index.php文件,写入以下代码 (这个文件就是api地址)
<?php
//存有链接的文件名,这里是存放图片链接的txt文件
$filename = "img.txt";
if(!file_exists($filename)){
die('文件不存在');
}
//从文本获取链接
$pics = [];
$fs = fopen($filename, "r");
while(!feof($fs)){
$line=trim(fgets($fs));
if($line!=''){
array_push($pics, $line);
}
}
//从数组随机获取链接
$pic = $pics[array_rand($pics)];
//返回指定格式
$type=$_GET['type'];
switch($type){
//JSON返回
case 'json':
header('Content-type:text/json');
die(json_encode(['pic'=>$pic]));
default:
die(header("Location: $pic"));
}