0、基本例子
一般流程:1、测试网站是否运行正常
//returns true,if domain is availible,false if not
function isDomainAvailible($domain)
{
//check,if a valid url is provided
if(!filter_var($domain,FILTER_VALIDATE_URL))
{
return false;
}
//initialize curl
$curlInit = curl_init($domain);
curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);
curl_setopt($curlInit,true);
curl_setopt($curlInit,CURLOPT_NOBODY,true);
//get answer
$response = curl_exec($curlInit);
curl_close($curlInit);
if ($response) return true;
return false;
}
2、可以代替file_gecontents的操作
curl_setopt($ch,0);
curl_setopt($ch,1); //Set curl to return the data instead of printing it to the browser.
curl_setopt($ch,$url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
3、保存某个网站下的所有图片
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应用
// the url contains most of the info needed
$url = "ftp://username:password@mydomain.com:21/path/to/new/file";
$ch = curl_init();
curl_setopt($ch,$url);
curl_setopt($ch,1);
// upload related options
curl_setopt($ch,CURLOPT_UPLOAD,1);
curl_setopt($ch,CURLOPT_INFILE,$fp);
curl_setopt($ch,CURLOPT_INFILESIZE,filesize("/path/to/file"));
// set for ASCII mode (e.g. text files)
curl_setopt($ch,CURLOPT_FTPASCII,1);
$output = curl_exec($ch);
curl_close($ch);
5、使用curl发送JSON数据
$ch = curl_init('http://api.local/rest/users');
curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"POST");
curl_setopt($ch,CURLOPT_POSTFIELDS,$data_string);
curl_setopt($ch,true);
curl_setopt($ch,CURLOPT_HTTPHEADER,array(
'Content-Type: application/json','Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);