Home  >  Article  >  Backend Development  >  PHP download pictures to local server instance sharing

PHP download pictures to local server instance sharing

小云云
小云云Original
2018-02-06 15:54:312913browse

This article mainly shares with you a method of replacing the image path in the article with PHP and downloading the image to the local server. It has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor to take a look, I hope it can help everyone.

php Replace the image path in the article and download the image to the local server

/**
 * 获取替换文章中的图片路径
 * @param string $xstr 内容
 * @param string $oriweb 网址
 * @return string
 *
 */
function replaceimg($xstr, $oriweb){
  //保存路径
  $d = date('Ymd', time());
  $saveimgfile_1 = '/uploads/allimg/'.$d;
  $dirslsitss = DEDEROOT.$saveimgfile_1;//分类是否存在
  if(!is_dir($dirslsitss)) {
    @mkdir($dirslsitss, 0777);
  }
  //匹配图片的src
  preg_match_all('#<img.*?src="([^"]*)"[^>]*>#i', $xstr, $match);
  foreach($match[1] as $imgurl){
    $imgurl = $imgurl;
    if(is_int(strpos($imgurl, 'http'))){
      $arcurl = $imgurl;
    } else {
      $arcurl = $oriweb.$imgurl;
    }
    $img=file_get_contents($arcurl);
    if(!empty($img)) {
      //保存图片到服务器
      $fileimgname = time()."-".rand(1000,9999).".jpg";
      $filecachs=$dirslsitss."/".$fileimgname;
      $fanhuistr = file_put_contents( $filecachs, $img );
      $saveimgfile = $saveimgfile_1."/".$fileimgname;
      $xstr=str_replace($imgurl,$saveimgfile,$xstr);
    }
  }
  return $xstr;
}

Related recommendations:

php regular match in the article Detailed explanation of remote image address and downloading images to local instance

WeChat development method of setting up camera, displaying images locally, uploading and downloading images

PHP How to use pcntl_fork to implement multi-process downloading of pictures

The above is the detailed content of PHP download pictures to local server instance sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn