phpcurl的几段小使用
时间:2021-07-01 10:21:17
帮助过:4人阅读
php curl的几段小应用
php 的CURL是不错的功能,下面收藏几段不错的片段?
1 测试网站是否运行正常?
??
Java代码?
?
- ??
- ??
- ??if?(isDomainAvailible('http://gz.itownet.cn'))??
- ???????{??
- ???????????????echo?"Up?and?running!";??
- ???????}??
- ???????else??
- ???????{??
- ???????????????echo?"Woops,?nothing?found?there.";??
- ???????}??
- ??
- ?????????
- ???????function?isDomainAvailible($domain)??
- ???????{??
- ?????????????????
- ???????????????if(!filter_var($domain,?FILTER_VALIDATE_URL))??
- ???????????????{??
- ???????????????????????return?false;??
- ???????????????}??
- ??
- ?????????????????
- ???????????????$curlInit?=?curl_init($domain);??
- ???????????????curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);??
- ???????????????curl_setopt($curlInit,CURLOPT_HEADER,true);??
- ???????????????curl_setopt($curlInit,CURLOPT_NOBODY,true);??
- ???????????????curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true);??
- ??
- ?????????????????
- ???????????????$response?=?curl_exec($curlInit);??
- ??
- ???????????????curl_close($curlInit);??
- ??
- ???????????????if?($response)?return?true;??
- ??
- ???????????????return?false;??
- ???????}??
- ?>??
2 可以代替file_gecontents的操作?
???
Java代码?
?
- function?file_get_contents_curl($url)?{??
- ????$ch?=?curl_init();??
- ??
- ????curl_setopt($ch,?CURLOPT_HEADER,?0);??
- ????curl_setopt($ch,?CURLOPT_RETURNTRANSFER,?1);???
- ????curl_setopt($ch,?CURLOPT_URL,?$url);??
- ??
- ????$data?=?curl_exec($ch);??
- ????curl_close($ch);??
- ??
- ????return?$data;??
- }??
3 保存某个网站下的所有图片?
??
Java代码?
?
- ??function?getImages($html)?{??
- ????$matches?=?array();??
- ????$regex?=?'~http://somedomain.com/images/(.*?)\.jpg~i';??
- ????preg_match_all($regex,?$html,?$matches);??
- ????foreach?($matches[1]?as?$img)?{??
- ????????saveImg($img);??
- ????}??
- }??
- ??
- function?saveImg($name)?{??
- ????$url?=?'http://somedomain.com/images/'.$name.'.jpg';??
- ????$data?=?get_data($url);??
- ????file_put_contents('photos/'.$name.'.jpg',?$data);??
- }??
- ??
- $i?=?1;??
- $l?=?101;??
- ??
- while?($i?$l)?{??
- ????$html?=?get_data('http://somedomain.com/id/'.$i.'/');??
- ????getImages($html);??
- ????$i?+=?1;??
- }??
4 FTP应用?
?
Java代码?
?
- ??
- $file?=?fopen("/path/to/file",?"r");??
- ??
- ??
- $url?=?"ftp://username:password@mydomain.com:21/path/to/new/file";??
- ??
- $ch?=?curl_init();??
- ??
- curl_setopt($ch,?CURLOPT_URL,?$url);??
- curl_setopt($ch,?CURLOPT_RETURNTRANSFER,?1);??
- ??
- ??
- curl_setopt($ch,?CURLOPT_UPLOAD,?1);??
- curl_setopt($ch,?CURLOPT_INFILE,?$fp);??
- curl_setopt($ch,?CURLOPT_INFILESIZE,?filesize("/path/to/file"));??
- ??
- ??
- curl_setopt($ch,?CURLOPT_FTPASCII,?1);??
- ??
- $output?=?curl_exec($ch);??
- curl_close($ch); ?
?