温馨提示: 这篇文章于2550天前编写,现在可能不再适用或落后.

一般网站都是使用apache或者nginx来设置图片防盗链,不过这样只是去检查Refresh来禁止访问的。不过这样的话,却不能100%防盗。

昨天想着是不是可以用php的gd库输出图片然后用session来进行防盗链呢?

session_start();
if(!isset($_GET['image'])){
    https404();
}
$imagePath = $_GET['image'];
if(!isset($_SESSION['image'])||$_SESSION['image']!=true){
    https403();
}else{
    if(is_file($imagePath)){
        if(!is_file($imagePath)){
            https403();
        }else{
            @output($imagePath);
        }
    }else{
        output($imagePath);
    }
}
function output($path){
    list($width,$height,$type) = getimagesize($path);
    $img = null;
    switch($type){
        case 1:$img = imagecreatefromgif($path);break;
        case 2:
            $img = imagecreatefromjpeg($path);break;
        case 3:
            $img = imagecreatefrompng($path);
            imagealphablending($img, true);
            imagesavealpha($img, true);
            break;

        case 6:
            $img = imagecreatefromwbmp($path);
        break;
        default:https500();
    }
    switch ($type) {
        case 2:
            header("Content-type: image/jpeg");
            imagejpeg($img);
            break;
        case 3:
            header("Content-type: image/png");
            imagepng($img);
            break;
        case 1:
            header("Content-type: image/gif");
            imagegif($img);
            break;
        case 6:
            header("Content-type: image/bmp");
            imagewbmp($img);
            break;
        default:
            https500();
    }
}
function https403(){
    header('HTTP/1.1 403 Forbidden');
    header('Status:403 Forbidden');
    exit;
}
function https500(){
    header('HTTP/1.1 500 Internal Server Error');
    header('Status:500 Internal Server Error');
    exit;
}
function https404(){
    header('HTTP/1.1 404 Not Found');
    header('Status:404 Not Found');
    exit;
}

代码如上。这段代码是利用get请求的image参数获取图片地址,然后根据浏览器是否有session来禁止访问,然后根据图片类型输出对应的图片。

然后在进入网站的时候设置session

201704291446001651

session_start();
$_SESSION['image'] = true;

这样就可以实现用session防盗,不过,,,,这个效率的话....我试了一下,最少都有200ms诶....算了为了效率还是用检测referer的方式来防盗吧.....或者直接readfile输出指定格式图片貌似比这个快点

    阁下需要登录后才可以查看评论哦~

    随便看看

      载入中...

      正在准备穿越次元,阁下请稍等片刻~