最近碰到图片上传下载的需求,汇总下:
1.上传图片
如果 php 版本为 5.4 及以下,图片地址可传参为:
$param['pic'] = '@/tmp/test.png';
如果版本大于 5.4,可以这样:
$pic = '/tmp/test.img';
$pic_info = explode('/', $pic);
$c_file = new \CURLFile($pic, 'image/jpeg', end($pic_info));
$param['pic'] = $c_file;
之所以如此区分,是因为 php 官方文档标明:
2.下载图片
/**
* @param $url: 图片远程地址
* @param $path: 本地保存路径
* @return string
*/
public static function downloadImage($url, $path)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$file = curl_exec($ch);
curl_close($ch);
$file_name = pathinfo($url, PATHINFO_BASENAME);
$resource = fopen($path . $file_name, 'a');
fwrite($resource, $file);
fclose($resource);
return $path. $file_name;
}
以上。
|