Home > Article > Backend Development > PHP download pictures to local server instance sharing
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 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!