php将远程图片保存到本地服务器的实现代码

PHP如何将远程图片本地化,本文分享了实现代码

rush:PHP;"> /**

  • 创建所有目录
  • @param string $truepath 真实地址
  • @param string $mmode 模式
  • @return bool
    */
    if ( ! function_exists('MkdirAll'))
    {
    function MkdirAll($truepath)
    { global $cfg_dir_purview;
    if(!file_exists($truepath))
    {
    mkdir($truepath,$cfg_dir_purview);
    chmod($truepath,$cfg_dir_purview);
    return true;
    }
    else
    {
    return true;
    }
    }
    }
    /**
  • 获得文章body里的外部资源
  • @access public
  • @param string $body 文档内容
  • @return string
    */
    function GetCurContent($body)
    {
    global $cfg_multi_site,$cfg_basehost,$cfg_basedir,$cfg_image_dir,$arcID,$cuserLogin,$dsql;
    $cfg_uploaddir = '/c';
    $basehost = "http://".$_SERVER["HTTP_HOST"];

$img_array = array();
preg_match_all("/src=[\"|'|\s]{0,}(http:\/\/([^>]*).(gif|jpg|png))/isU",$body,$img_array);

$img_array = array_unique($img_array[1]);
$imgurl = $cfg_uploaddir.'/'.date("ymd",time());
$imgPath = $cfg_basedir.$imgurl;
if(!is_dir($imgPath.'/'))
{
MkdirAll($imgPath,$GLOBALS['cfg_dir_purview']);
CloseFtp();
}
$milliSecond = date('His',time());
foreach($img_array as $key=>$value)
{
if(preg_match("#".$basehost."#i",$value))
{
continue;
}
if(preg_match("#".$basehost."#i",$value))
{
continue;
}
if(!preg_match("#^http:\/\/#i",$value))
{
continue;
}

$http=pget($value,'$value',true); 
$itype=($http['head']['content_type']); 
if(!preg_match("#\.(jpg|gif|png)#i",$itype)) 
{ 
  if($itype=='image/gif') 
  { 
    $itype = ".gif"; 
  } 
  else if($itype=='image/png') 
  { 
    $itype = ".png"; 
  } 
  else 
  { 
    $itype = '.jpg'; 
  } 
} 
$milliSecondN = rand(1000,9999).rand(1000,9999); 
$value = trim($value); 
$rndFileName = $imgPath.'/'.$milliSecondN.'-'.$key.$itype; 
$fileurl = $<a href="https://www.jb51.cc/tag/imgur/" target="_blank" class="keywords">imgur</a>l.'/'.$milliSecondN.'-'.$key.$itype; 

$tp = fopen($rndFileName,'wb'); 
fwrite($tp,$http['data']); 
fclose($tp); 

if(file_exists($cfg_basedir.$fileurl)) 
{ 
  $info = ''; 
  $imginfos = Ge<a href="https://www.jb51.cc/tag/timage/" target="_blank" class="keywords">timage</a>Size($rndFileName,$info); 
  $fsize = filesize($rndFileName); 
  $body = str_replace($value,$fileurl,$body); 

} 

}
return $body;
}

//调用方式
echo GetCurContent($body);

以上就是实现远程图片本地化的全部代码,希望对大家的学习有所帮助。

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...