加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

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

发布时间:2020-05-23 20:20:16 所属栏目:PHP 来源:互联网
导读:有些时候我们想保存一些漂亮图片,但又不想手动去保存下来,尤其是大批量的存储,这个时候我们需要写一段程序来帮助我们完成这个工作,本文介绍了php如何将远程图片本地化,需要的朋友可以参考下

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 = $imgUrl.'/'.$milliSecondN.'-'.$key.$itype; 

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

if(file_exists($cfg_basedir.$fileurl)) 
{ 
  $info = ''; 
  $imginfos = GetImageSize($rndFileName,$info); 
  $fsize = filesize($rndFileName); 
  $body = str_replace($value,$fileurl,$body); 

} 

}
return $body;
}

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

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

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读