阿里云刷新CDN缓存

PHP版本的刷新阿里云CDN缓存最小SDK


define('DebugModel', true);
define('AccessKeyId', 'AccessKeyId');
define('AccessKeySecret', 'AccessKeySecret');

/**
 *  刷新网址
 */
function freshURL($urls = [], $type = 'File')
{
    $sign = getSign(['Action' => 'RefreshObjectCaches', 'ObjectPath' => formatURL($urls), 'ObjectType' => $type]);
    $url = 'https://cdn.aliyuncs.com/?' . $sign['url'] . '&Signature=' . $sign['sign'];
    $request = json_decode(httpRequest($url));
    if (isset($request->Code) && $request->Code == 'OK') {
        return true;
    } else {
        if (DebugModel) {
            var_dump($request);
        }
        return false;
    }
}

/**
 *  格式化网址
 */
function formatURL($urls = [])
{
    $urls = array_map(function($v) {
        return str_replace(['http://', 'https://'], ['', ''], $v);
    }, $urls);
    return implode('\n', $urls);
}

/**
 *  获取签名
 */
function getSign($add)
{
    $data = array(
        "Version" => "2018-05-10",
        "SignatureMethod" => "HMAC-SHA1",
        "SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
        "SignatureVersion" => "1.0",
        "AccessKeyId" => AccessKeyId,
        "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
        "Format" => "JSON",
    );
    $data = array_merge($data, $add);
    ksort($data);
    $format = http_build_query($data);
    $signUrl = 'GET&%2F&' . urlencode(str_replace(['+', '*', '%7E'], ['%20', '%2A', '~'], $format));
    $sign = urlencode(base64_encode(hash_hmac('sha1', $signUrl, AccessKeySecret . '&', true)));
    return array('url' => $format, 'sign' => $sign);
}

/**
 *  发起 HTTP 请求
 */
function httpRequest($url)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    $data = curl_exec($curl);
    $error = curl_error($curl);
    curl_close($curl);
    if ($error) {
        return $error;
    } else {
        return $data;
    }
}

function main() {
    freshURL(['https://abc.com/login/', 'https://abc.com/user/12']);
}

main();