手把手教你制作随机图API

发布于 2020-09-17  2,646 次阅读


内容纲要

我们常常看到别人的网站打开会出现随机的图片,如:
https://acg.xydwz.cn/random/初音未来壁纸1.php
https://api.r10086.com/动漫综合1.php
这样的骚操作是怎么完成的呢,下边由我来教你如何制作随机图API

首先在桌面建立一个名为api的文件夹,然后在文件夹里新建一个index.php的文件,文件内容为:

<?php
//存有链接的文件名
$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"));
}

保存之后再新建一个文本文件,名为img.txt,
之后将要上传的图片链接写入,每行一个链接,如

https://cdn.jsdelivr.net/gh/Jony6688/picture/img/1599832276502.png
https://cdn.jsdelivr.net/gh/Jony6688/picture/img/1597306978509.png
https://cdn.jsdelivr.net/gh/Jony6688/picture/img/1599832339719.png
https://cdn.jsdelivr.net/gh/Jony6688/picture/img/1599832357602.png

最后将整个api的文件夹上传到网站目录,打开之后就会出现随机图啦!
成品展示:http://api.jonyblog.cn/API/index.php

  • alipay_img
  • wechat_img
届ける言葉を今は育ててる
最后更新于 2020-09-17