1.file_put_contents,file_get_contents

$url = 'http://example.com/image.jpg';
$img = '/my/folder/flower.jpg';                    //路径加新的文件名,也可以为相对路径
file_put_contents($img, file_get_contents($url));

备注:allow_url_fopen配置项需要为true

2.copy

copy('http://example.com/image.jpg', 'local/folder/flower.jpg');

3.curl

$ch = curl_init('http://example.com/image.jpg');
$fp = fopen('/my/folder/flower.jpg', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

4.加入调试信息

$img = "";
$img = file_get_contents($image);
echo $img; //for debugging..
//for running..
if(!$img) die("no data fetched");

如果$img有数据,再写入

$result = file_put_contents($target_path,$img);
if($result=== FALSE) 
  die("Error writing data into $target_path");
else
  echo "$result bytes written to $target_path";

解析链接中的文件名及后缀

$url = 'http://www.example.com.cn/abc/de/fg.php?id=1';
$arr = parse_url($url);
$file = basename($arr['path']);
echo $file;                              //输出:fg.php

如果图片成功下载,但是发现大小为0,
检查file_get_contents图片路径是否为相对路径,字符串拼接出绝对路径即可

作者 铁血 汉子 2018年1月7日
2024/05/05/12:00:57pm 2018/1/7/5:12:23
0 3185