做网站时,出于某种需要,我们可能需要限制某些地区或者某个时段对网站的访问,下面是一段简单的php脚本,记录、分享下。

/**
 * Created by PhpStorm.
 * User: William.Wei
 * Email: weizhansheng@outlook.com
 * Date: 2016/3/2
 * Time: 21:54
 */
header("Content-type: text/html; charset=utf-8");
date_default_timezone_set('PRC');
$hour = date('H');
if ($hour > 6 && $hour < 20) {
    function referrer_contains($antecedents, $referrer_keys)
    {
        if (!$antecedents) {
            return false;
        }
        foreach ($referrer_keys as $referrer_key) {
            if (strpos($antecedents, $referrer_key) !== false) {
                return true;
            }
        }
        return false;
    }

    if (!referrer_contains($_SERVER['HTTP_REFERER'], ['baidu', 'google', 'sm.cn', 'so.com', 'sogou', 'poorren.com']) && strpos($_SERVER['HTTP_USER_AGENT'], 'spider') === false) {
        $verification = ['广东省', '浙江省', '北京市'];
        $address = json_decode(file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=" . $_SERVER['REMOTE_ADDR']), true);
        if (!$address || in_array($address['data'] ? $address['data']['region'] : '', $verification)) {
            exit;
        }
    }
}

具体用途,大可发挥想象。