API 站点里很常见的随机图接口,适合做头像、壁纸、二次元图、封面图接口。代码支持两种模式:默认返回 JSON,传 ?type=redirect 时直接 302 跳转到图片地址。
使用方式:把代码保存为 random-image.php,同级新建 images 目录并放入 jpg/png/webp/gif 图片。
<?php
declare(strict_types=1);
header('Access-Control-Allow-Origin: *');
$baseUrl = 'http://127.0.0.1:8000';
$imageDir = __DIR__ . '/images';
$allowedExt = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
function json_response(array $data, int $status = 200): void
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
if (!is_dir($imageDir)) {
json_response(['code' => 500, 'message' => 'images 目录不存在'], 500);
}
$files = [];
foreach (scandir($imageDir) ?: [] as $file) {
if ($file === '.' || $file === '..') {
continue;
}
$path = $imageDir . '/' . $file;
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (is_file($path) && in_array($ext, $allowedExt, true)) {
$files[] = $file;
}
}
if (!$files) {
json_response(['code' => 404, 'message' => '暂无图片'], 404);
}
$pick = $files[random_int(0, count($files) - 1)];
$imageUrl = rtrim($baseUrl, '/') . '/images/' . rawurlencode($pick);
if (($_GET['type'] ?? '') === 'redirect') {
header('Location: ' . $imageUrl, true, 302);
exit;
}
json_response([
'code' => 0,
'message' => 'ok',
'data' => [
'url' => $imageUrl,
'filename' => $pick,
'count' => count($files),
],
]); 本地测试:
# 启动服务
php -S 127.0.0.1:8000 random-image.php
# JSON 模式
curl 'http://127.0.0.1:8000/random-image.php'
# 直接跳转模式
curl -I 'http://127.0.0.1:8000/random-image.php?type=redirect'