对着gpt一顿输出复制粘贴又反问造出来的东西,将图片url缓存到apcu
我没学过php,应该效率还算可以吧
image-20230618001452890

<?php

// 授权令牌
$token = "Bearer ";

// 特定相册ID
$albumId = 5; // 替换成实际的相册ID

$ttl = 604800;

/**
 * 获取指定页码的图片列表
 *
 * @param string $token 授权令牌
 * @param int $albumId 相册ID
 * @param int $page 页码
 * @return array 图片列表数组
 */
function getImageListByPage($token, $albumId, $page)
{
    // 获取特定相册的图片列表
    $url = "https://img.xxxx.xx/api/v1/images?album_id=" . $albumId . "&page=" . $page;
    $headers = array(
        "Authorization: " . $token,
        "Accept: application/json"
    );

    // 发起请求获取图片数据
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);

    $result = json_decode($response, true);

    if ($result["status"] && isset($result["data"]) && !empty($result["data"])) {
        return $result["data"];
    } else {
        return array();
    }
}

/**
 * 获取随机图片URL
 *
 * @param string $token 授权令牌
 * @param int $albumId 相册ID
 * @param int $ttl ttl
 * @return string|null 随机图片URL,如果无法获取则返回null
 */
function getRandomImageUrl($token, $albumId, $ttl)
{
    // 从APCu缓存中获取图片URL列表
    $cacheKey = 'image_urls_' . $albumId;
    $imageUrls = apcu_fetch($cacheKey, $success);

    if (!$success) {
        // APCu缓存中不存在数据,重新获取并缓存数据

        // 获取图片列表的总页数
        $lastPage = 1;
        $currentPage = 1;
        $imageUrls = array();

        while ($currentPage <= $lastPage) {
            // 获取指定页码的图片列表
            $imageList = getImageListByPage($token, $albumId, $currentPage);

            if (isset($imageList["last_page"])) {
                $lastPage = $imageList["last_page"];
            }

            if (isset($imageList["data"]) && !empty($imageList["data"])) {
                foreach ($imageList["data"] as $image) {
                    // 将图片的URL存储到数组中
                    $imageUrls[] = $image["links"]["url"];
                }
            }

            // 更新当前页码
            $currentPage++;
        }

        // 将图片URL列表存储到APCu缓存中
        apcu_store($cacheKey, $imageUrls, $ttl);
    } else {
        // 发送命中缓存的响应头
        header('X-Cache: APCu Hit');
    }

    if (!empty($imageUrls)) {
        // 从图片URL列表中随机选择一张图片的URL
        $randomImageUrl = $imageUrls[array_rand($imageUrls)];
        return $randomImageUrl;
    }

    return null;
}

// 获取随机图片URL
$imageUrl = getRandomImageUrl($token, $albumId, $ttl);

if ($imageUrl) {
    // 发送302重定向响应
    header("Location: " . $imageUrl);
    exit;
} else {
    echo "null";
}
僕と契約して、魔法少女になってよ!
最后更新于 2024-01-18