另一些有用的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); }
|