chenhao
首页
栏目
标签
关于
友链
废话少说,放码过来
php如何下载远程图片/文件到本地服务器
thinkphp
php
程序人生
发布日期: 2021-09-01 10:36:42
喜欢量: 26 个
阅读次数:
718
php如何下载远程图片/文件到本地服务器
```php <?php /** * @describe:下载远程图片到本地 */ public function downLongFile() { $type = $this->request->param("type"); $url = $this->request->param("url"); $d = date("Ymd", time()); $save_dir = ROOT_PATH . "public"; $dk = "/hhy/" . $d . "/"; $save_dir .= $dk; $ext = strrchr($url, '.'); $filename = time() . $ext; if (!is_dir($save_dir)) { @mkdir($save_dir, 0777, true); } try { if ($type == 1) { ob_start(); $img = file_get_contents($url); ob_end_clean(); $fp2 = @fopen($save_dir . $filename, "a"); fwrite($fp2, $img); fclose($fp2); unset($img, $url); } elseif ($type == 2) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // 自动设置Referer curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); $file = curl_exec($ch); curl_close($ch); file_put_contents($save_dir . $filename, $file); } elseif ($type == 3) { $file = file_get_contents($url); file_put_contents($save_dir . $filename, $file); } elseif ($type == 4) { $ch = curl_init(); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_URL, $url); ob_start(); curl_exec($ch); $return_content = ob_get_contents(); ob_end_clean(); $fp = @fopen($save_dir . $filename, "a"); //将文件绑定到流 fwrite($fp, $return_content); //写入文件 fclose($fp); } $u = request()->domain() . $dk . $filename; $this->success($u); } catch (Exception $exception) { $this->error($exception->getMessage()); } } ```
文章作者:
chenhao
文章链接:
http://chenhaoblog.com/show/NA==
版权声明:
本博客所有文章除特別声明外,转载请注明来源
chenhaoBlog
!
分享: