PHP搭建随机图片api

knoci 发布于 2025-02-07 87 次阅读


云服务器PHP搭建随机图片api

创建PHP环境

​ 想要搭建随机图片api,就要有php环境,我们在1panel面板可以直接拉起一个PHP运行环境,模板可以不选节省空间

image-20241130234348446

​ 然后我们选择 创建网站运行环境,选中我们之前创建的PHP环境,名字和端口无所谓,主域名就是你想搭建的随机图片api的域名

image-20241130234642719

修改index.php

之后我们把index.php改成下面的代码,其中$weburl改成你的域名

<?php
// 允许跨域访问
header('Access-Control-Allow-Origin: *');

// 设置站点地址
$weburl = 'https://your.domain.com/'; // 修改为您的域名
$pcPath = 'pc'; // 电脑端图片路径
$mobilePath = 'mobile'; // 移动端图片路径

// 函数:从目录中获取图片列表
function getImagesFromDir($path) {
    $images = array();
    if ($img_dir = @opendir($path)) {
        while (false!== ($img_file = readdir($img_dir))) {
            // 匹配webp、jpg、jpeg、png等常见图片格式,添加i忽略大小写
            if (preg_match("/(.webp|.jpg|.jpeg|.png)$/i", $img_file)) { 
                $images[] = $img_file;
            }
        }
        closedir($img_dir);
    }
    return $images;
}

// 检测用户代理以区分手机和电脑访问
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$isMobile = preg_match('/(android|iphone|ipad|ipod|blackberry|windows phone)/i', $userAgent);

// 根据访问设备设置图片路径
$path = $isMobile? $mobilePath : $pcPath;

// 缓存图片列表
$imgList = getImagesFromDir($_SERVER['DOCUMENT_ROOT']. '/'. $path); // 确保路径是正确的

// 如果没有图片,返回错误信息
if (empty($imgList)) {
    header("HTTP/1.0 404 Not Found");
    echo "No images found in the directory.";
    exit;
}

// 从列表中随机选择一张图片
shuffle($imgList);
$img = reset($imgList);

// 获取图片的扩展名,用于后续设置正确的Content-Type
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
// 根据不同的图片扩展名设置对应的Content-Type头部信息
switch ($ext) {
    case 'webp':
        $contentType = 'image/webp';
        break;
    case 'jpeg':
        $contentType = 'image/jpeg';
        break;
    case 'png':
        $contentType = 'image/png';
        break;
    default:
        $contentType = 'image/jpg'; 
}

// 直接输出所选的随机图片
$img_path = $path. '/'. $img;
$img_url = $weburl. $img_path;
header('Content-Type: '. $contentType); // 设置正确的Content-Type
readfile($_SERVER['DOCUMENT_ROOT']. '/'. $img_path); // 确保文件路径是正确的
?>

​ 创建pc和mobile两个文件夹,代码会识别访问的设备类型,然后从两个文件夹之一取图片,电脑大图就放在pc文件夹,手机竖图放在mobile文件夹

image-20241201000348091

​ 最后在DNS解析中添加上的域名,这样我们就搭建好了一个随机图片api

image-20241130235913094

​ 如果要支持https访问,需要申请证书和开启https

image-20241201000521053

​ 之后我们访问随机图片api,图片能够正常显示。

image-20241201000624918

结尾

​ 如果想要图片加载更快,可以考虑挂CDN加速~