function saveRemote($fieldName, $savePath = 'temp/'){ $allowFiles = [".png", ".jpg", ".jpeg", ".gif", ".bmp", "webp"]; $imgUrl = htmlspecialchars($fieldName); $imgUrl = str_replace("&","&",$imgUrl); //http开头验证 if(strpos($imgUrl,"http") !== 0){ $data=array( 'state' => '链接不是http链接', ); return json_encode($data); } //获取请求头并检测死链 $heads = get_headers($imgUrl); if(!(stristr($heads[0],"200") && stristr($heads[0],"OK"))){ $data=array( 'state' => '链接不可用', ); return json_encode($data); } //格式验证(扩展名验证和Content-Type验证) if(preg_match("/^http(s?):\/\/(mmbiz.qpic.cn|qimg.91ud.com)\/(.*)/", $imgUrl) != 1){ $fileType = strtolower(strrchr($imgUrl,'.')); if(!in_array($fileType,$allowFiles) || stristr($heads['Content-Type'],"image")){ $data=array( 'state' => '链接contentType不正确', ); return json_encode($data); } } //打开输出缓冲区并获取远程图片 ob_start(); $context = stream_context_create( array('http' => array( 'follow_location' => false // don't follow redirects )) ); readfile($imgUrl,false,$context); $img = ob_get_contents(); ob_end_clean(); preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/",$imgUrl,$m); $dirname = './'.UPLOAD_PATH.'remote/'.date('Y/m/d').'/'; $file['oriName'] = $m ? $m[1] : ""; $file['filesize'] = strlen($img); $file['ext'] = strtolower(strrchr('remote.png','.')); $file['name'] = uniqid().$file['ext']; $file['fullName'] = $dirname.$file['name']; $fullName = $file['fullName']; //检查文件大小是否超出限制 if($file['filesize'] >= 10240000){ $data=array( 'state' => '文件大小超出网站限制', ); return json_encode($data); } //创建目录失败 if(!file_exists($dirname) && !mkdir($dirname,0777,true)){ $data=array( 'state' => '目录创建失败', ); return json_encode($data); }else if(!is_writeable($dirname)){ $data=array( 'state' => '目录没有写权限', ); return json_encode($data); } //移动文件 if(!(file_put_contents($fullName, $img) && file_exists($fullName))){ //移动失败 $data=array( 'state' => '写入文件内容错误', ); return json_encode($data); }else{ //移动成功 $data=array( 'state' => 'SUCCESS', 'url' => substr($file['fullName'],1), 'title' => $file['name'], 'original' => $file['oriName'], 'type' => $file['ext'], 'size' => $file['filesize'], ); $ossConfig = tpCache('oss'); if ($ossConfig['oss_switch']) { //图片可选择存放在oss $savePath = $savePath.date('Y/m/d/'); $object = UPLOAD_PATH.$savePath.md5(getTime().uniqid(mt_rand(), TRUE)).'.'.pathinfo($data['url'], PATHINFO_EXTENSION); $getRealPath = ltrim($data['url'], '/'); $ossClient = new \app\common\logic\OssLogic; $return_url = $ossClient->uploadFile($getRealPath, $object); if (!$return_url) { $state = "ERROR" . $ossClient->getError(); $return_url = ''; } else { $state = "SUCCESS"; } @unlink($getRealPath); $data['url'] = $return_url; } } return json_encode($data); }