| 
 另一些有用的cURL 选项 
HTTP 认证 
如果某个URL请求需要基于 HTTP 的身份验证,你可以使用下面的代码: 复制内容到剪贴板代码: 
$url = "http://www.somesite.com/members/"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 发送用户名和密码 curl_setopt($ch, CURLOPT_USERPWD, "myusername:mypassword"); // 你可以允许其重定向 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 下面的选项让 cURL 在重定向后 // 也能发送用户名和密码 curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, 1); $output = curl_exec($ch); curl_close($ch); 
FTP 上传 
PHP 自带有 FTP 类库, 但你也能用 cURL: 
// 开一个文件指针 $file = fopen("/path/to/file", "r"); // url里包含了大部分所需信息 $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")); // 是否开启ASCII模式 (上传文本文件时有用) curl_setopt($ch, CURLOPT_FTPASCII, 1); $output = curl_exec($ch); curl_close($ch); 
翻墙术 
你可以用代理发起cURL请求: 
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL,'http://www.example.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 指定代理地址 curl_setopt($ch, CURLOPT_PROXY, '11.11.11.11:8080'); // 如果需要的话,提供用户名和密码 curl_setopt($ch, CURLOPT_PROXYUSERPWD,'user:pass'); $output = curl_exec($ch); curl_close ($ch); 
回调函数 
可以在一个URL请求过程中,让cURL调用某指定的回调函数。例如,在内容或者响应下载的过程中立刻开始利用数据,而不用等到完全下载完。 
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL,'http://net.tutsplus.com'); curl_setopt($ch, CURLOPT_WRITEFUNCTION,"progress_function"); curl_exec($ch); curl_close ($ch); function progress_function($ch,$str) {     echo $str;     return strlen($str); } 
这个回调函数必须返回字串的长度,不然此功能将无法正常使用。 
在URL响应接收的过程中,只要收到一个数据包,这个函数就会被调用。 
小结 
今天我们一起学习了cURL库的强大功能和灵活的扩展性。希望你喜欢。下一次要发起URL请求时,考虑下cURL吧! 
经典论坛交流: http://bbs.blueidea.com/thread-2966700-1-1.html 
本文链接:http://www.blueidea.com/tech/program/2010/7348.asp  
出处:蓝色理想
 
责任编辑:moby 
上一页 基于PHP的cURL快速入门 [5] 下一页 
◎进入论坛网络编程版块参加讨论
	       |