PHP 获取每日BING图 并且缓存URL链接到本地JSON

远昔 代码记录 2021-08-16 3277 0

将获取的BING图链接进行缓存,减少服务器负担,提升访问速度。

<?php
$filename = "./bing.json";
if (file_exists($filename) === false) {
    file_put_contents($filename, "");
}
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle); 
$contents = json_decode($contents, true);
if (filesize($filename) === 0) {
    getBingImg();
} else {
    if ($contents['time'] === date("Ymd")) {
        Header("Location: " . $contents['url']);
    } else {
        getBingImg();
    }
}
function getBingImg()
{
    $str = json_decode(file_get_contents('https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1'));
    if (isset($str->images[0])) {
        $impurely = 'https://cn.bing.com' . $str->images[0]->url;
    } else {
        $impurely = false;
    }
    if ($impurely) {
        global $contents;
        if ($contents['url'] !== $impurely) {
            global $filename;
            $data = array(
                "time" => date("Ymd"),
                "url" => $impurely
            );
            $data = json_encode($data);
            file_put_contents($filename, $data);
        }
        Header("Location: " . $impurely);
        exit();
    } else {
        exit('error');
    }
}
?>


评论

发表评论:

挤眼 亲亲 咆哮 开心 想想 可怜 糗大了 委屈 哈哈 小声点 右哼哼 左哼哼 疑问 坏笑 赚钱啦 悲伤 耍酷 勾引 厉害 握手 耶 嘻嘻 害羞 鼓掌 馋嘴 抓狂 抱抱 围观 威武 给力
提交评论

清空信息
关闭评论