php保存远程图片
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.zzzyk.com/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);
}
哈这样的话就可以保存远程有图片防盗的主机的图片了喽.
补充:Php教程,Php高级应用