转载:http://www.phpchina.com/article-40161-1.html,作者撩得不错,记录一下。
//通过curl进行GET请求的案例
<?php
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "https://github.com/search?q=react");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
//echo output
echo $output;
// close curl resource to free up system resources
curl_close($ch);
?>
//通过curl进行post请求的例子
<?php
$data='{"name":"Lei","msg":"Are you OK?"}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://测试服务器的IP马赛克/testRespond.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length:' . strlen($data)));
curl_setopt($ch, CURLOPT_POSTFIELDS , $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
echo $output;
curl_close($ch);
?>
//上传图片
<?php
$data = array('name'=>'boy', "upload"=>"");
$ch = curl_init();
$data['upload']=new CURLFile(realpath(getcwd().'/boy.png'));
curl_setopt($ch, CURLOPT_URL, "http://115.29.247.189/test/testRespond.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_POSTFIELDS , $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
echo $output;
curl_close($ch);
?>
//下载图片
<?php
$ch = curl_init();
$fp=fopen('./girl.jpg', 'w');
curl_setopt($ch, CURLOPT_URL, "http://远程服务器地址马赛克/girl.jpg");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_FILE, $fp);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
fclose($fp);
$size = filesize("./girl.jpg");
if ($size != $info['size_download']) {
echo "下载的数据不完整,请重新下载";
} else {
echo "下载数据完整";
}
curl_close($ch);
?>
//HTTP认证
function curl_auth($url,$user,$passwd){
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_USERPWD => $user.':'.$passwd,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true
]);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$authurl = 'http://要请求HTTP认证的地址';
echo curl_auth($authurl,'vace','passwd');