1
在PHP中使用curl下载和保存图片
Posted by 撒得一地 on 2015年12月27日 in PHP笔记
上一篇: 6个超级有用的PHP代码片段
下一篇: PHP命名规则总结
下一篇: PHP命名规则总结
curl,PHP中使用拓展的libcurl功能,它允许在许多不同类型的协议下,仍然能和不同类型的服务进行连接和交流。libcurl目前支持http、https、ftp、gopher、telnet、dict、file和ldap协议。libcurl还支持https证书,http post,http put,ftp 上传等,支持一系列基于http上传,代理(proxies),cookies和用户名加密码身份验证。
下面将介绍一个有用的实例,你可以使用php和curl,将另外一个站点服务器上的图片保存到你的站点。通过下面提供的这个脚本,你只要通过修改站点url,就可以将你添加的站点上的图片保存到你的服务器上。
具体脚步代码:
<?php
function makeCurlCall($url){
$curl = curl_init();
$timeout = 5;
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,$timeout);
curl_setopt($curl,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
function getImages($html) {
$matches = array();
$url_regex = '~http://somedomain.com/images/(.*?)\.jpg~i';
preg_match_all($url_regex, $html, $matches);
foreach ($matches[1] as $img) {
saveImages($img);
}
}
function saveImages($name) {
$url = 'http://somedomain.com/images/'.$name.'.jpg';
$data = makeCurlCall($url);
file_put_contents('photos/'.$name.‘.jpg’, $data);
}
$i = 1;
$l = 10;
while ($i < $l) {
$html = makeCurlCall('http://somedomain.com/id/'.$i.'/');
getImages($html);
$i += 1;
}
?>
上一篇: 6个超级有用的PHP代码片段
下一篇: PHP命名规则总结
下一篇: PHP命名规则总结
1 Comment
厉害curl这一块还没有学到过!看看谢谢博主