既然玩博客,随机图肯定会用到,前前后后用了不少共用的API,我感觉有几点不好的地方

  1. 服务不可控,随时可能挂掉,而且有的很慢
  2. 图片不一定喜欢,而且也无法更换
  3. API资源也不太好找

基于以上三个方面,决定自己搭建一个随机图片API,简单使用,可随时增减照片,服务可用性也更可控

搭建也非常简单,一共二步就搞定了

第一步:宝塔创建网站

我这里域名使用:api.lovelu.top,也可自定义为自己域名,记得添加解析

注意:无需添加反代及伪静态

第二步:初始化目录

  • 根目录新建index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
const ALLOW_RAW_OUTPUT = false;
// 是否开启 ?raw 选项,可能会消耗服务器较多流量

function has_query($query)
{
return isset($_GET[$query]);
}

if (file_exists(__DIR__ . '/url.csv')) // in the same folder
$imgs_array = file(__DIR__ . '/url.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
else if (file_exists('../url.csv')) // in the parent folder
$imgs_array = file('../url.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
else // for vercel runtime
$imgs_array = file('http://' . $_SERVER['HTTP_HOST'] . '/url.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if (count($imgs_array) == 0) $imgs_array = array('https://http.cat/503');


$id = has_query('id') ? $_GET['id'] : "";
if (strlen($id) > 0 && is_numeric($id)) {
settype($id, 'int');
$len = count($imgs_array);
if ($id >= $len || $id < 0) {
$id = array_rand($imgs_array);
} else {
header('Cache-Control: public, max-age=86400');
}
} else {
header('Cache-Control: no-cache');
$id = array_rand($imgs_array);
}


if (has_query('json')) {
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
echo json_encode(array('id' => $id, 'url' => $imgs_array[$id]));
} else if (has_query('raw')) {
if (!ALLOW_RAW_OUTPUT) {
header('HTTP/1.1 403 Forbidden');
exit();
}
header('Content-Type: image/png');
echo file_get_contents($imgs_array[$id]);
} else {
header('Referrer-Policy: no-referrer');
header('Location: ' . $imgs_array[$id]);
}

exit();
  • 根目录新建url.csv

用来存放图片url,一行一个,内容如下

1
2
https://img.lovelu.top/random/1.jpg
https://img.lovelu.top/random/2.jpg

初始化好了,如图即可

此时访问你https://api.lovelu.top,就可以看到随机图片了,大家也去试试吧