刘明野

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

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

<?php
/*
    * @author www.liumingye.cn
*/
$filename = "./cache.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) {
    // echo "获取\r\n";
    getBingImg();
} else {
    if ($contents['time'] === date("Ymd")) {
        // echo "缓存\r\n";
        Header("Location: ".$contents['url']);
    } else {
        // echo "过期\r\n";
        getBingImg();
    }
}
function getBingImg() {
    $str = file_get_contents('http://cn.bing.com/HPImageArchive.aspx?idx=0&n=1');
    if (preg_match("/<url>(.+?)<\/url>/ies", $str, $matches)) {
        $imgurl = 'https://cn.bing.com' . $matches[1];
    }
    if ($imgurl) {
        global $contents;
        if($contents['url'] !== $imgurl){
            global $filename;
            $data = array(
                "time" => date("Ymd") ,
                "url" => $imgurl
            );
            $data = json_encode($data);
            file_put_contents($filename, $data);
        }
        Header("Location: ".$imgurl);
        exit();
    } else {
        exit('error');
    }
}
本文为作者刘明野发布,未经允许禁止转载!
14943
3
11
发表留言

    yj
    7月前

    这是什么地方

    QwerityQ
    3年前

    哇∠( ᐛ 」∠)_

    3年前

    我擦牛逼

友情链接