php 如何保存个图片,php下载图片并保存

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图片路径是否为相对路径,字符串拼接出绝对路径即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值