先读取网络图片,然后保存到本地,再生成本地服务器地址供使用
相关代码:
/*START*保存远程图片到本地*2015-8-25*/
if (strpos($post[‘bodys’][‘content’], ‘http://’) !== false || strpos($post[‘bodys’][‘content’], ‘https://’) !== false) {
$description = $post[‘bodys’][‘content’];
preg_match_all (“/<img([^>]*)\s*src=(‘|\”)([^’\”]+)(‘|\”)/”, $description, $matches );
//去除数组中重复的值
$new_arr=array_unique($matches[3]);
foreach ($new_arr as $value) {
$img = $this->grabImage($value, ”);
if ($img) {
$description = str_replace($value, $img, $description);
}
}
$post[‘bodys’][‘content’] = $description;
}
/*END*保存远程图片到本地*2015-8-25*/
function grabImage($url, $filename = ”) {
if ($url == ”) {
return false;
}
if ($filename == ”) {
$ext = strrchr($url, ‘.’);
if($ext != ‘.gif’ && $ext != ‘.jpg’ && $ext != ‘.png’) {
return false;
}
//uniqid()基于当前时间微秒数
$uniqid = uniqid();
$filename = $_SERVER[‘DOCUMENT_ROOT’].’kut/public/images/articles/’.$uniqid.$ext;
$realpath = ‘http://’.$_SERVER[‘SERVER_NAME’].’/kut/public/images/articles/’.$uniqid.$ext;
}
ob_start();
readfile($url);
$img = ob_get_contents();
ob_end_clean();
$fp = @fopen($filename, “a”);
fwrite($fp, $img);
fclose($fp);
return $realpath;
}