在互联网中,我们常常需要快速获取各类图片资源。今天,就为大家带来一个超实用的教程,教你轻松搭建属于自己的随机图片获取API,从此告别四处寻觅图片API的繁琐。
1.新建文件api.php
<?php
// 使用__DIR__常量获取当前脚本所在目录,并拼接文件路径
$filename = __DIR__. '/img.txt';
if (!file_exists($filename)) {
die('文件不存在');
}
// 打开文件并检查是否成功
$fs = fopen($filename, "r");
if (!$fs) {
die('无法打开文件');
}
// 从文本获取链接
$pics = [];
while (!feof($fs)) {
$line = trim(fgets($fs));
if ($line!== '') {
array_push($pics, $line);
}
}
fclose($fs);
// 从数组随机获取链接
$pic = $pics[array_rand($pics)];
// 获取type参数
$type = isset($_GET['type'])? $_GET['type'] : '';
switch ($type) {
// JSON返回
case 'json':
header('Content - type:text/json');
die(json_encode(['pic' => $pic]));
default:
// 验证链接是否合法
if (!filter_var($pic, FILTER_VALIDATE_URL)) {
die('无效的图片链接');
}
die(header("Location: $pic"));
}
2.新建文件img.txt
http://example.com/image1.jpg
http://example.com/image2.jpg
http://example.com/image3.jpg
访问你的网址/api.php访问就可以实现了,api.php和 img.txt 理想存放目录是在同一目录下。
如果将img.txt放于特定目录。此时,需在api.php中修改$filename变量指定完整路径,如:
$filename = '/var/www/wwwroot/data/img.txt';
<?php
$img_array = glob("images/*.{gif,jpg,png}", GLOB_BRACE);
if (!empty($img_array)) {
$img = array_rand($img_array);
$dz = $img_array[$img];
header("Location: " . $dz);
exit; // 重定向后终止脚本执行
} else {
echo "没有找到符合条件的图片文件。";
}
?>
图片丢到images文件夹下,访问api.php即可
来源:白衣博客