随机图片API

利用[relit]中的PHP搭建随机图片API

必需

一个GIthub账号
一个relit账号
了解git、php

创建

创建GIthub仓库

仓库必要文件

.replit
index.php
img.txt

.replit源码如下

1
2
run = "php -S 0.0.0.0:8000 -t ."
entrypoint = "index.php"

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

?>

relit拉取仓库并部署

所遇到的问题

1、