本文最后更新于2023年2月21日,已超过 1 年没有更新,如果文章内容失效,请 反馈 给我们,谢谢!
随机图库API接口PHP源码
<?php
//存有链接的文件名
$filename = "RandomPic.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"));
}
附:必应每日壁纸API
<?php
$str = file_get_contents('http://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1');
$array = json_decode($str);
$imgurl = 'https://cn.bing.com'.$array->{"images"}[0]->{"url"};//图片URL
if($imgurl){
header('Location: '.$imgurl);
exit();
}else{
exit('error');
}
?>
随机图库API接口PHP源码第二款(2023/02/21)
<?php
$folder='/images/';//在服务器自己建个文件,并存放照片!
//存放图片文件的位置
$path = $_SERVER['DOCUMENT_ROOT']."/".$folder;
$files=array();
if ($handle=opendir("$path")) {
while(false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(substr($file,-3)=='gif' || substr($file,-3)=='jpg') $files[count($files)] = $file;
}
}
}
closedir($handle);
$random=rand(0,count($files)-1);
if(substr($files[$random],-3)=='gif') header("Content-type: image/gif");
elseif(substr($files[$random],-3)=='jpg') header("Content-type: image/jpeg");
readfile("$path/$files[$random]");
?>