PHP 下載遠程網頁圖片並且儲存在本地執行個體

來源:互聯網
上載者:User


fopen函數執行個體

ob_start : 開啟輸出緩衝

readfile : 讀入一個檔案並寫入到輸出緩衝
返回從檔案中讀入的位元組數。如果出錯返回 FALSE 並且除非是以 @readfile() 形式調用,否則會顯示錯誤資訊。

ob_get_contents : Return the contents of the output buffer(返回輸出緩衝的內容)
This will return the contents of the output buffer without clearing it or FALSE, if output buffering isn’t active. (如果輸出緩衝沒有活動(開啟),則返回 FALSE)

ob_end_clean() : Clean (erase) the output buffer and turn off output buffering(清除輸出緩衝)

 代碼如下 複製代碼


<?php
//URL是遠端完整圖片地址,不可為空, $filename 是另存新檔的圖片名字
//預設把圖片放在以此指令碼相同的目錄裡
function GrabImage($url,$filename=""){
        if($url == ""){
            return false;
        }
       
        $ext=strrchr($url,".");
       
        if($ext != ".gif" && $ext != ".jpg" && $ext != ".bmp" && $ext != ".png"){
            echo "格式不支援!";
            return false;
        }
       
        if($filename == ""){
            $filename = time()."$ext";
        }
       
        ob_start();
        readfile($url);
        $img=ob_get_contents();
        ob_end_clean();
        $size=strlen($img);
        $fp2=fopen($filename,"a");
        if(fwrite($fp2,$img) === false){
            echo "不能寫入檔案".$filename;
            exit();
        }else{
            echo "儲存圖片成功!";
        }
        fclose($fp2);
        return $filename;
       
    }
//測試
GrabImage("/logo.png","as.png");
?>


php下載遠程圖片函數 可偽造來路


$gurl 要下載的圖片地址
$rfurl 來路。如果靶心圖表像做了防盜鏈設定,可以繞過。
$filename 下載圖片儲存的檔案名稱,相對路徑,不要用realpath
$gcookie 調整cookie 偽造的cookie
$JumpCount 跳轉計數
$maxtime 最大次數
調用方法:DownImageKeep(“yun_qi_img/baidu_jgylogo2.gif”,”http://baidu.com”,”a.gif”,”",0,10);

 代碼如下 複製代碼

function DownImageKeep($gurl, $rfurl, $filename, $gcookie=”", $JumpCount=0, $maxtime=30)
{
$urlinfos = GetHostInfo($gurl);
$ghost = trim($urlinfos['host']);
if($ghost==”)
{
return FALSE;
}
$gquery = $urlinfos['query'];
if($gcookie==”" && !empty($rfurl))
{
$gcookie = RefurlCookie($rfurl);
}
$sessionQuery = “GET $gquery HTTP/1.1rn”;
$sessionQuery .= “Host: $ghostrn”;
$sessionQuery .= “Referer: $rfurlrn”;
$sessionQuery .= “Accept: */*rn”;
$sessionQuery .= “User-Agent: Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)rn”;
if($gcookie!=”" && !preg_match(“/[rn]/”, $gcookie))
{
$sessionQuery .= $gcookie.”rn”;
}
$sessionQuery .= “Connection: Keep-Alivernrn”;
$errno = “”;
$errstr = “”;
$m_fp = fsockopen($ghost, 80, $errno, $errstr,10);
fwrite($m_fp,$sessionQuery);
$lnum = 0;

//擷取應答頭
$m_httphead = Array();
$httpstas = explode(” “,fgets($m_fp,256));
$m_httphead["http-edition"] = trim($httpstas[0]);
$m_httphead["http-state"] = trim($httpstas[1]);
while(!feof($m_fp))
{
$line = trim(fgets($m_fp,256));
if($line == “” || $lnum>100)
{
break;
}
$hkey = “”;
$hvalue = “”;
$v = 0;
for($i=0; $i {
if($v==1)
{
$hvalue .= $line[$i];
}
if($line[$i]==”:”)
{
$v = 1;
}
if($v==0)
{
$hkey .= $line[$i];
}
}
$hkey = trim($hkey);
if($hkey!=”")
{
$m_httphead[strtolower($hkey)] = trim($hvalue);
}
}

if(preg_match(“/^3/”, $m_httphead["http-state"]))
{
if(isset($m_httphead["location"]) && $JumpCount<3) { $JumpCount++; DownImageKeep($gurl,$rfurl,$filename,$gcookie,$JumpCount); } else { return FALSE; } } if(!preg_match(“/^2/”, $m_httphead["http-state"])) { return FALSE; } if(!isset($m_httphead)) { return FALSE; } $contentLength = $m_httphead['content-length']; //儲存圖片 $fp = fopen($filename,”w”) or die(“寫入檔案:{$filename} 失敗!”); $i=0; $okdata = “”; $starttime = time(); while(!feof($m_fp)) { $okdata .= fgetc($m_fp); $i++; //逾時退出 if(time()-$starttime>$maxtime)
{
break;
}

//到達指定大小結束
if($i >= $contentLength)
{
break;
}
}
if($okdata!=”")
{
fwrite($fp,$okdata);
}
fclose($fp);
if($okdata==”")
{
@unlink($filename);
fclose($m_fp);
return FALSE;
}
fclose($m_fp);
return TRUE;
}
//獲得網址的host和query部份
function GetHostInfo($gurl)
{
$gurl = preg_replace(“/^http:///i”, “”, trim($gurl));
$garr['host'] = preg_replace(“//(.*)$/i”, “”, $gurl);
$garr['query'] = “/”.preg_replace(“/^([^/]*)//i”, “”, $gurl);
return $garr;
}
//獲得頁面返回的Cookie資訊
function RefurlCookie($gurl)
{
global $gcookie,$lastRfurl;
$gurl = trim($gurl);
if(!empty($gcookie) && $lastRfurl==$gurl)
{
return $gcookie;
}
else
{
$lastRfurl=$gurl;
}
if(trim($gurl)==”)
{
return ”;
}
$urlinfos = GetHostInfo($gurl);
$ghost = $urlinfos['host'];
$gquery = $urlinfos['query'];
$sessionQuery = “GET $gquery HTTP/1.1rn”;
$sessionQuery .= “Host: $ghostrn”;
$sessionQuery .= “Accept: */*rn”;
$sessionQuery .= “User-Agent: Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)rn”;
$sessionQuery .= “Connection: Closernrn”;
$errno = “”;
$errstr = “”;
$m_fp = fsockopen($ghost, 80, $errno, $errstr,10) or die($ghost.’
‘);
fwrite($m_fp,$sessionQuery);
$lnum = 0;

//擷取詳細應答頭
$gcookie = “”;
while(!feof($m_fp))
{
$line = trim(fgets($m_fp,256));
if($line == “” || $lnum>100)
{
break;
}
else
{
if(preg_match(“/^cookie/i”, $line))
{
$gcookie = $line;
break;
}
}
}
fclose($m_fp);
return $gcookie;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.