如何在线下载并保存远程服务器上的图片文件?
- 内容介绍
- 文章标签
- 相关推荐
本文共计252个文字,预计阅读时间需要2分钟。
php函数:下载远程图片参数:$url - 网络图片地址参数:$dir - 保存文件目录参数:$timeout - 超时时间(默认60秒)返回:布尔值或错误信息
function http_down($url, $dir, $timeout=60) { preg_match('//', $url); if ($match) { return URL格式错误; }
$filename=basename($url); $file_path=$dir . '/' . $filename;
$ch=curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); $data=curl_exec($ch); $error=curl_error($ch); $httpcode=curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
if ($error) { return 下载失败: . $error; }
if ($httpcode !=200) { return 下载失败: HTTP状态码 . $httpcode; }
if (!file_put_contents($file_path, $data)) { return 保存文件失败; }
return true;}
下载远程图片/** * 下载远程文件 * @param string $url 网址 * @param string $filename 保存文件名 * @param integer $timeout 过期时间 * return boolean|string */ function http_down($url, $dir, $timeout = 60) { preg_match('/mmbiz_[\w]+/i', $url,$a); $ext = explode('_', $a[0])[1]; $filename = $dir.md5(time().mt_rand()).'.'.$ext; ini_set('php_curl','on'); $path = dirname($filename); if (!is_dir($path) && !mkdir($path, 0755, true)) { return false; } $fp = fopen($filename, 'w'); $ch = curl_init($url); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_exec($ch); curl_close($ch); fclose($fp); return $filename; }
本文共计252个文字,预计阅读时间需要2分钟。
php函数:下载远程图片参数:$url - 网络图片地址参数:$dir - 保存文件目录参数:$timeout - 超时时间(默认60秒)返回:布尔值或错误信息
function http_down($url, $dir, $timeout=60) { preg_match('//', $url); if ($match) { return URL格式错误; }
$filename=basename($url); $file_path=$dir . '/' . $filename;
$ch=curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); $data=curl_exec($ch); $error=curl_error($ch); $httpcode=curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
if ($error) { return 下载失败: . $error; }
if ($httpcode !=200) { return 下载失败: HTTP状态码 . $httpcode; }
if (!file_put_contents($file_path, $data)) { return 保存文件失败; }
return true;}
下载远程图片/** * 下载远程文件 * @param string $url 网址 * @param string $filename 保存文件名 * @param integer $timeout 过期时间 * return boolean|string */ function http_down($url, $dir, $timeout = 60) { preg_match('/mmbiz_[\w]+/i', $url,$a); $ext = explode('_', $a[0])[1]; $filename = $dir.md5(time().mt_rand()).'.'.$ext; ini_set('php_curl','on'); $path = dirname($filename); if (!is_dir($path) && !mkdir($path, 0755, true)) { return false; } $fp = fopen($filename, 'w'); $ch = curl_init($url); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_exec($ch); curl_close($ch); fclose($fp); return $filename; }

