PHP下载远程图片的几种方法总结
微wx笑2019-09-04 14:03:50【编程语言】人已围观关键字:
php
PHP下载远程图片的几种方法总结1、使用file_get_contentsfunction dlfile($file_url, $save_to){ $content = file_get_contents($file_url); file_put_contents($save_to,
PHP下载远程图片的几种方法总结
1、使用file_get_contents
function dlfile($file_url, $save_to) { $content = file_get_contents($file_url); file_put_contents($save_to, $content); }
2、使用CURL
function dlfile($file_url, $save_to) { $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 0); curl_setopt($ch,CURLOPT_URL,$file_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $file_content = curl_exec($ch); curl_close($ch); $downloaded_file = fopen($save_to, 'w'); fwrite($downloaded_file, $file_content); fclose($downloaded_file); }
3、使用fopen
function dlfile($file_url, $save_to) { $in= fopen($file_url, "rb"); $out= fopen($save_to, "wb"); while ($chunk = fread($in,8192)) { fwrite($out, $chunk, 8192); } fclose($in); fclose($out); }
4、使用readfile
参考:
/** * 拉取远程图片 * @return mixed */ private function saveRemote() { $imgUrl = htmlspecialchars($this->fileField); $imgUrl = str_replace("&", "&", $imgUrl); //http开头验证 if (strpos($imgUrl, "http") !== 0) { $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK"); return; } preg_match('/(^https*:\/\/[^:\/]+)/', $imgUrl, $matches); $host_with_protocol = count($matches) > 1 ? $matches[1] : ''; // 判断是否是合法 url if (!filter_var($host_with_protocol, FILTER_VALIDATE_URL)) { $this->stateInfo = $this->getStateInfo("INVALID_URL"); return; } preg_match('/^https*:\/\/(.+)/', $host_with_protocol, $matches); $host_without_protocol = count($matches) > 1 ? $matches[1] : ''; // 此时提取出来的可能是 ip 也有可能是域名,先获取 ip $ip = gethostbyname($host_without_protocol); // 判断是否是私有 ip if(!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) { $this->stateInfo = $this->getStateInfo("INVALID_IP"); return; } //获取请求头并检测死链 $heads = get_headers($imgUrl, 1); if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) { $this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK"); return; } //格式验证(扩展名验证和Content-Type验证) $fileType = strtolower(strrchr($imgUrl, '.')); if (strpos($fileType, "?")){ $fileType = strstr($fileType, "?", true); } if (!isset($heads['Content-Type']) || !stristr($heads['Content-Type'], "image")) { $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE"); return; }else{ if (count($this->config['allowFiles']) > 0){ if (!in_array($fileType, $this->config['allowFiles'])){ //$this->stateInfo = $this->getStateInfo("ERROR_HTTP_ALLOWFILES").$heads['Content-Type']; //image/webp return; } } } //打开输出缓冲区并获取远程图片 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(); $imgUrl2 = $imgUrl; if (strpos($imgUrl, "?")){ $imgUrl2 = substr($imgUrl, 0, strripos($imgUrl, "?")); } preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl2, $m); $this->oriName = $m ? $m[1]:""; $this->fileSize = strlen($img); $this->fileType = $this->getFileExt(); $this->fullName = $this->getFullName(); $this->filePath = $this->getFilePath(); $this->fileName = $this->getFileName(); $dirname = dirname($this->filePath); //检查文件大小是否超出限制 if (!$this->checkSize()) { $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED"); return; } //创建目录失败 if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) { $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR"); return; } else if (!is_writeable($dirname)) { $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE"); return; } //移动文件 if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败 $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT"); } else { //移动成功 $this->stateInfo = $this->stateMap[0]; } }
下载与保存完整方法:
private function downloadImage($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); $file = curl_exec($ch); curl_close($ch); $this->saveAsImage($url, $file); } private function saveAsImage($url, $file) { $filename = pathinfo($url, PATHINFO_BASENAME); $dirname = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_DIRNAME); $path = 'public' . $dirname . '/'; $fullpath = 'public' . $dirname . '/' . $filename; // 如果目录不存在,则创建 if(!is_dir($path)) { mkdir($path, 0777, true); } if(file_exists($fullpath)) { //$this->output->writeln("【已存在】输出路径" . $fullpath); } else { $resource = fopen($fullpath, 'a'); fwrite($resource, $file); fclose($resource); //$this->output->writeln("【已保存】输出路径" . $fullpath); } }
本文由 微wx笑 创作,采用 CC BY-NC 4.0 许可协议。 非商业性使用可自由转载、引用、甚至修改,但需署名作者且注明出处。