php保存遠程圖片,下面這段代碼是我自己寫的,但是有一個問題就是放在服務器就保存圖片的成功不是很高,我用的是file_get_contents來取得,最後發現如果主機有防盜的就讀取了
php保存遠程圖片,下面這段代碼是我自己寫的,但是有一個問題就是放在服務器就保存圖片的成功不是很高,我用的是file_get_contents來取得,最後發現如果主機有防盜的就讀取了,我們欺騙主機的方法來做,就是用fsockopen向主機發送一個用戶包
function get_remote($body){
set_time_limit(0);
$img_array = array();
$img_path = "get_pic/";
preg_match_all("/(src|SRC)=["|'| ]{0,}(http://(.*).(gif|jpg|jpeg|png))/isU",$body,$img_array);
$img_array = array_unique($img_array[2]);
foreach ($img_array as $key => $value) {
$get_file = @file_get_contents($value);
$filetime = time();
!is_dir($img_path) ? mkdir($img_path) : null;
$filename = date("YmdHis",$filetime).rand(1,999).'.'.substr($value,-3,3);
if(empty($get_file)){
sleep(3);
$get_file = @file_get_contents($value);
if(empty($get_file)){
$body = preg_replace("/".addcslashes($value,"/")."/isU", 'http://www.111cn.cn/notfound.jpg', $body);
continue;
}
}
if(!empty($get_file) ){
$fp = fopen($img_path.$filename,"w");
if(fwrite($fp,$get_file)){
$body = preg_replace("/".addcslashes($value,"/")."/isU", $img_path.$filename, $body);
}
}
fclose($fp);
sleep(1);
}
//$body =str_replace('<img','<input class="" type="image" ',$body);
//$body =str_replace('<IMG','<input class="" type="image" ',$body);
return $body;
}
下面我們來看看fsockopen的方法喽.
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!=""&&!ereg("[rn]",$gcookie)) $sessionQuery .= $gcookie."rn";
$sessionQuery .= "Connection: Keep-Alivernrn";
$errno = "";
$errstr = "";
$url ='http://www.moko.cc';
$m_fp = fsockopen($url,80,$errno,$errstr,10);
fwrite($m_fp,$sessionQuery);
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.'<br />');
fwrite($m_fp,$sessionQuery);
$lnum = 0;
//獲取詳細應答頭
$gcookie = "";
while(!feof($m_fp)){
$line = trim(fgets($m_fp,256));
if($line == "" || $lnum>100) break;
else{
if(eregi("^cookie",$line)){
$gcookie = $line;
break;
}
}
}
fclose($m_fp);
}
哈這樣的話就可以保存遠程有圖片防盜的主機的圖片了喽.