在做ueditor百度编辑器复制粘贴文章时,包括网页文章含图片,以及P微信公众文章图片时不能自动本地化,原来是微信公众号的图片地址没有后缀
微信公众号图片地址有防盗下载,
如:有PNG或jpg
https://mmbiz.qpic.cn/mmbiz_png/zOnV3yQxrautMWFVnqM39Roxo6Kw4wCEWoRelVw3e0cdg8Oph4y34pmOibTHiaheiaD8mUsPOZerpc7OVS7aNqcPQ/0?wx_fmt=png
https://mmbiz.qpic.cn/mmbiz_jpg/vu4IdQ8iaORjdfOibL3g10iapWgqxGG1j8I23ocVOY5CacA02ZWJkkHGJ6JV8E1h178edW8d3VRgCplA0amgoJ3Mw/640?wx_fmt=jpeg&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1
所以思路就是,把公众号图片网址https选替换成http, 原因是https有防盗无法下载。
然后,用curl下载图片,保存时注意看mmbiz_jpg或mmbiz_png自己补充后缀,本地化后,为了让百度ueditor编辑器能自动替换,需求把图片网址还原成https,且htmlspecialchars_decode解码下,thinkphp把url被encode过了。
源码:
//微信公众号图片本地化ayumi if(strpos($imgUrl,'mmbiz.qpic.cn')!=false) { $imgUrl = str_replace('https','http',$imgUrl);//https替换成http,否则防盗链无法通过 $savePath = $config['savePath']; $referer_url = 'https://mp.weixin.qq.com'; //创建保存位置 if (!file_exists($savePath)) { mkdir("$savePath", 0777, true); } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $imgUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); if(!empty($referer_url)) { curl_setopt ($ch, CURLOPT_REFERER, $referer_url); //构造来路 } if(!empty($ip)) { $headers['CLIENT-IP'] = $ip; $headers['X-FORWARDED-FOR'] = $ip; $headerArr = array(); foreach( $headers as $n => $v ) { $headerArr[] = $n .':' . $v; } curl_setopt ($ch, CURLOPT_HTTPHEADER, $headerArr); //构造IP } if(!empty($user_agent)) { $user_agent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"; curl_setopt ($ch, CURLOPT_USERAGENT, $user_agent); //构造用户端代理 } //$status = curl_getinfo($ch,CURLINFO_HTTP_CODE); //获取url响应 $file = curl_exec($ch); curl_close($ch); //不存在 if (preg_match("/404/", $file)){ return false; } $get_img = getimagesize($imgUrl); $suffix = '.jpg'; if(strpos($imgUrl,'mmbiz_png')!=false) { $suffix = '.png'; } $filename = uniqid().rand(100,999).'_'.$get_img[0].'x'.$get_img[1].$suffix; $resource = fopen($savePath . $filename, 'a'); fwrite($resource, $file); fclose($resource); $file = "/upload/ueditor/" . $date . "/" . $filename; $imgUrl = str_replace('http://','https://',$imgUrl);//替换回原来https,保证图片地址和原来一样,ueditor编辑器能自动替换src $return_img['source'] = htmlspecialchars_decode($imgUrl);//替换回原来https,保证图片地址和原来一样,ueditor编辑器能自动替换src $return_img['state'] = 'SUCCESS'; $return_img['url'] = $file; array_push($list, $return_img); continue; }