?

首先,我们建立一组需要测试的URL,接着指定一组需要测试的浏览器信息">

首頁  >  文章  >  php教程  >  php的cURL库介绍

php的cURL库介绍

WBOY
WBOY原創
2016-06-06 19:46:411098瀏覽

cURL 是一个利用URL语法规定来传输文件和数据的工具,支持很多协议,如HTTP、FTP、TELNET等。很多小偷程序都是使用这个函数。 最爽的是,PHP也支持 cURL 库。本文将介绍 cURL 的一些高级特性,以及在PHP中如何运用它。? 正文: cURL 是一种功能强大的库,支

cURL 是一个利用URL语法规定来传输文件和数据的工具,支持很多协议,如HTTP、FTP、TELNET等。很多小偷程序都是使用这个函数。
最爽的是,PHP也支持 cURL 库。本文将介绍 cURL 的一些高级特性,以及在PHP中如何运用它。?

正文:
cURL 是一种功能强大的库,支持很多不同的协议、选项,能提供 URL 请求相关的各种细节信息。

启用 cURL 设置
首先,我们得先要确定我们的PHP是否开启了这个库,你可以通过使用php_info()函数来得到这一信息。

﹤?<span>php
</span><span>phpinfo</span><span>();
</span>?﹥

如果你可以在网页上看到下面的输出,那么表示cURL库已被开启。

php的cURL库介绍

如果你看到的话,那么你需要设置你的PHP并开启这个库。如果你是在Windows平台下,那么非常简单,你需要改一改你的php.ini文件的设置,找到php_curl.dll,并取消前面的分号注释就行了。如下所示:

<span>//</span><span>取消下面的注释</span>
extension=php_curl.dll

如果你是在Linux下面,那么,你需要重新编译你的PHP了,编辑时,你需要打开编译参数——在configure命令上加上“–with-curl” 参数。

为什么要用 cURL?
是的,我们可以通过其他办法获取网页内容。大多数时候,我因为想偷懒,都直接用简单的PHP函数:

<span>$content</span> = <span>file_get_contents</span>("http://www.doucube.com"<span>);
</span><span>//</span><span> or</span>
<span>$lines</span> = <span>file</span>("http://www.doucube.com"<span>);
</span><span>//</span><span> or</span>
<span>readfile</span>(http:<span>//</span><span>www.doucube.com);</span>

不过,这种做法缺乏灵活性和有效的错误处理。而且,你也不能用它完成一些高难度任务——比如处理coockies、验证、表单提交、文件上传等等。

基本结构

在学习更为复杂的功能之前,先来看一下在PHP中建立cURL请求的基本步骤:

php的cURL库介绍

<span>//</span><span> 1. 初始化</span>
<span>$ch</span> =<span> curl_init();
</span><span>//</span><span> 2. 设置选项,包括URL</span>
curl_setopt(<span>$ch</span>, CURLOPT_URL, "http://www.doucube.com"<span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_RETURNTRANSFER, 1<span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_HEADER, 0<span>);
</span><span>//</span><span> 3. 执行并获取HTML文档内容</span>
<span>$output</span> = curl_exec(<span>$ch</span><span>);
</span><span>//</span><span> 4. 释放curl句柄</span>
curl_close(<span>$ch</span>);

php的cURL库介绍

第二步(也就是 curl_setopt() )最为重要,一切玄妙均在此。有一长串cURL参数可供设置,它们能指定URL请求的各个细节。要一次性全部看完并理解可能比较困难,所以今天我们只试一下那些更常用也更有用的选项。

检查错误
你可以加一段检查错误的语句(虽然这并不是必需的):

<span>//</span><span> ...</span>
<span>$output</span> = curl_exec(<span>$ch</span><span>);
</span><span>if</span> (<span>$output</span> === <span>FALSE</span><span>) {
</span><span>echo</span> "cURL Error: " . curl_error(<span>$ch</span><span>);
}
</span><span>//</span><span> ...</span>

请注意,比较的时候我们用的是“=== FALSE”,而非“== FALSE”。因为我们得区分 空输出 和 布尔值FALSE,后者才是真正的错误。

获取信息
这是另一个可选的设置项,能够在cURL执行后获取这一请求的有关信息:

<span>//</span><span> ...</span>
curl_exec(<span>$ch</span><span>);
</span><span>$info</span> = curl_getinfo(<span>$ch</span><span>);
</span><span>echo</span> '获取'. <span>$info</span>['url'] . '耗时'. <span>$info</span>['total_time'] . '秒'<span>;
</span><span>//</span><span> ...</span>

返回的数组中包括了以下信息:

php的cURL库介绍

“url” <span>//</span><span>资源网络地址 </span>
“content_type” <span>//</span><span>内容编码 </span>
“http_code” <span>//</span><span>HTTP状态码 </span>
“header_size” <span>//</span><span>header的大小 </span>
“request_size” <span>//</span><span>请求的大小 </span>
“filetime” <span>//</span><span>文件创建时间 </span>
“ssl_verify_result” <span>//</span><span>SSL验证结果 </span>
“redirect_count” <span>//</span><span>跳转技术 </span>
“total_time” <span>//</span><span>总耗时 </span>
“namelookup_time” <span>//</span><span>DNS查询耗时 </span>
“connect_time” <span>//</span><span>等待连接耗时 </span>
“pretransfer_time” <span>//</span><span>传输前准备耗时 </span>
“size_upload” <span>//</span><span>上传数据的大小 </span>
“size_download” <span>//</span><span>下载数据的大小 </span>
“speed_download” <span>//</span><span>下载速度 </span>
“speed_upload” <span>//</span><span>上传速度 </span>
“download_content_length”<span>//</span><span>下载内容的长度 </span>
“upload_content_length” <span>//</span><span>上传内容的长度 </span>
“starttransfer_time” <span>//</span><span>开始传输的时间 </span>
“redirect_time”<span>//</span><span>重定向耗时 </span>

php的cURL库介绍

?

基于浏览器的重定向
在第一个例子中,我们将提供一段用于侦测服务器是否有基于浏览器的重定向的代码。例如,有些网站会根据是否是手机浏览器甚至用户来自哪个国家来重定向网页。
我们利用 CURLOPT_HTTPHEADER 选项来设定我们发送出的HTTP请求头信息(http headers),包括user agent信息和默认语言。然后我们来看看这些特定网站是否会把我们重定向到不同的URL。

php的cURL库介绍

<span>//</span><span> 测试用的URL</span>
<span>$urls</span> = <span>array</span><span>(
</span>"http://www.doucube.com",
"http://www.mozilla.com",
"http://www.facebook.com"<span>
);
</span><span>//</span><span> 测试用的浏览器信息</span>
<span>$browsers</span> = <span>array</span><span>(
    </span>"standard" => <span>array</span><span> (
        </span>"user_agent" => "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6 (.NET CLR 3.5.30729)",
        "language" => "en-us,en;q=0.5"<span>
    )</span>,
    "iphone" => <span>array</span><span> (
        </span>"user_agent" => "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A537a Safari/419.3",
        "language" => "en"<span>
    )</span>,
    "french" => <span>array</span><span> (
        </span>"user_agent" => "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; GTB6; .NET CLR 2.0.50727)",
        "language" => "fr,fr-FR;q=0.5"<span>
    )
);
</span><span>foreach</span> (<span>$urls</span> <span>as</span> <span>$url</span><span>) {
    </span><span>echo</span> "URL: <span>$url</span>\n"<span>;
    </span><span>foreach</span> (<span>$browsers</span> <span>as</span> <span>$test_name</span> => <span>$browser</span><span>) {
        </span><span>$ch</span> =<span> curl_init();
        </span><span>//</span><span> 设置 url</span>
        curl_setopt(<span>$ch</span>, CURLOPT_URL, <span>$url</span><span>);
        </span><span>//</span><span> 设置浏览器的特定header</span>
        curl_setopt(<span>$ch</span>, CURLOPT_HTTPHEADER, <span>array</span><span>(
        </span>"User-Agent: {<span>$browser</span>['user_agent']}",
        "Accept-Language: {<span>$browser</span>['language']}"<span>
        ));
        </span><span>//</span><span> 页面内容我们并不需要</span>
        curl_setopt(<span>$ch</span>, CURLOPT_NOBODY, 1<span>);
        </span><span>//</span><span> 只需返回HTTP header</span>
        curl_setopt(<span>$ch</span>, CURLOPT_HEADER, 1<span>);
        </span><span>//</span><span> 返回结果,而不是输出它</span>
        curl_setopt(<span>$ch</span>, CURLOPT_RETURNTRANSFER, 1<span>);
        </span><span>$output</span> = curl_exec(<span>$ch</span><span>);
        curl_close(</span><span>$ch</span><span>);
        </span><span>//</span><span> 有重定向的HTTP头信息吗?</span>
        <span>if</span> (<span>preg_match</span>("!Location: (.*)!", <span>$output</span>, <span>$matches</span><span>)) {
            </span><span>echo</span> "<span>$test_name</span>: redirects to <span>$matches</span>[1]\n"<span>;
        } </span><span>else</span><span> {
            </span><span>echo</span> "<span>$test_name</span>: no redirection\n"<span>;
        }
    }
    </span><span>echo</span> "\n\n"<span>;
}</span>

php的cURL库介绍

?

首先,我们建立一组需要测试的URL,接着指定一组需要测试的浏览器信息。最后通过循环测试各种URL和浏览器匹配可能产生的情况。
因为我们指定了cURL选项,所以返回的输出内容则只包括HTTP头信息(被存放于 $output 中)。利用一个简单的正则,我们检查这个头信息中是否包含了“Location:”字样。

用POST方法发送数据
当发起GET请求时,数据可以通过“查询字串”(query string)传递给一个URL。例如,在google中搜索时,搜索关键即为URL的查询字串的一部分:
http://www.google.com/search?q=nettuts
这种情况下你可能并不需要cURL来模拟。把这个URL丢给“file_get_contents()”就能得到相同结果。?
不过有一些HTML表单是用POST方法提交的。这种表单提交时,数据是通过 HTTP请求体(request body) 发送,而不是查询字串。例如,当使用CodeIgniter论坛的表单,无论你输入什么关键字,总是被POST到如下页面:
http://codeigniter.com/forums/do_search/
你可以用PHP脚本来模拟这种URL请求。首先,新建一个可以接受并显示POST数据的文件,我们给它命名为post_output.php:
print_r($_POST);
接下来,写一段PHP脚本来执行cURL请求:

php的cURL库介绍

<span>$url</span> = "http://localhost/post_output.php"<span>;
</span><span>$post_data</span> = <span>array</span><span> (
</span>"foo" => "bar",
"query" => "Nettuts",
"action" => "Submit"<span>
);
</span><span>$ch</span> =<span> curl_init();
curl_setopt(</span><span>$ch</span>, CURLOPT_URL, <span>$url</span><span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_RETURNTRANSFER, 1<span>);
</span><span>//</span><span> 我们在POST数据哦!</span>
curl_setopt(<span>$ch</span>, CURLOPT_POST, 1<span>);
</span><span>//</span><span> 把post的变量加上</span>
curl_setopt(<span>$ch</span>, CURLOPT_POSTFIELDS, <span>$post_data</span><span>);
</span><span>$output</span> = curl_exec(<span>$ch</span><span>);
curl_close(</span><span>$ch</span><span>);
</span><span>echo</span> <span>$output</span>;

php的cURL库介绍

这段脚本发送一个POST请求给 post_output.php ,这个页面 $_POST 变量并返回,我们利用cURL捕捉了这个输出。

文件上传
上传文件和前面的POST十分相似。因为所有的文件上传表单都是通过POST方法提交的。
首先新建一个接收文件的页面,命名为 upload_output.php:
print_r($_FILES);
以下是真正执行文件上传任务的脚本:

php的cURL库介绍

<span>$url</span> = "http://localhost/upload_output.php"<span>;
</span><span>$post_data</span> = <span>array</span><span> (
</span>"foo" => "bar",
<span>//</span><span> 要上传的本地文件地址</span>
"upload" => "@C:/doucube/www/test.zip"<span>
);
</span><span>$ch</span> =<span> curl_init();
curl_setopt(</span><span>$ch</span>, CURLOPT_URL, <span>$url</span><span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_RETURNTRANSFER, 1<span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_POST, 1<span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_POSTFIELDS, <span>$post_data</span><span>);
</span><span>$output</span> = curl_exec(<span>$ch</span><span>);
curl_close(</span><span>$ch</span><span>);
</span><span>echo</span> <span>$output</span>;

php的cURL库介绍

如果你需要上传一个文件,只需要把文件路径像一个post变量一样传过去,不过记得在前面加上@符号。

cURL批处理(multi cURL)
cURL还有一个高级特性——批处理句柄(handle)。这一特性允许你同时或异步地打开多个URL连接。
下面是来自来自php.net的示例代码:

php的cURL库介绍

<span>//</span><span> 创建两个cURL资源</span>
<span>$ch1</span> =<span> curl_init();
</span><span>$ch2</span> =<span> curl_init();
</span><span>//</span><span> 指定URL和适当的参数</span>
curl_setopt(<span>$ch1</span>, CURLOPT_URL, "http://lxr.php.net/"<span>);
curl_setopt(</span><span>$ch1</span>, CURLOPT_HEADER, 0<span>);
curl_setopt(</span><span>$ch2</span>, CURLOPT_URL, "http://www.php.net/"<span>);
curl_setopt(</span><span>$ch2</span>, CURLOPT_HEADER, 0<span>);
</span><span>//</span><span> 创建cURL批处理句柄</span>
<span>$mh</span> =<span> curl_multi_init();
</span><span>//</span><span> 加上前面两个资源句柄</span>
curl_multi_add_handle(<span>$mh</span>,<span>$ch1</span><span>);
curl_multi_add_handle(</span><span>$mh</span>,<span>$ch2</span><span>);
</span><span>//</span><span> 预定义一个状态变量</span>
<span>$active</span> = <span>null</span><span>;
</span><span>//</span><span> 执行批处理</span>
<span>do</span><span> {
</span><span>$mrc</span> = curl_multi_exec(<span>$mh</span>, <span>$active</span><span>);
} </span><span>while</span> (<span>$mrc</span> ==<span> CURLM_CALL_MULTI_PERFORM);
</span><span>while</span> (<span>$active</span> && <span>$mrc</span> ==<span> CURLM_OK) {
</span><span>if</span> (curl_multi_select(<span>$mh</span>) != -1<span>) {
</span><span>do</span><span> {
</span><span>$mrc</span> = curl_multi_exec(<span>$mh</span>, <span>$active</span><span>);
} </span><span>while</span> (<span>$mrc</span> ==<span> CURLM_CALL_MULTI_PERFORM);
}
}
</span><span>//</span><span> 关闭各个句柄</span>
curl_multi_remove_handle(<span>$mh</span>, <span>$ch1</span><span>);
curl_multi_remove_handle(</span><span>$mh</span>, <span>$ch2</span><span>);
curl_multi_close(</span><span>$mh</span>);

php的cURL库介绍

这里要做的就是打开多个cURL句柄并指派给一个批处理句柄。然后你就只需在一个while循环里等它执行完毕。

这个示例中有两个主要循环。第一个 do-while 循环重复调用 curl_multi_exec() 。这个函数是无隔断(non-blocking)的,但会尽可能少地执行。它返回一个状态值,只要这个值等于常量 CURLM_CALL_MULTI_PERFORM ,就代表还有一些刻不容缓的工作要做(例如,把对应URL的http头信息发送出去)。也就是说,我们需要不断调用该函数,直到返回值发生改变。
而接下来的 while 循环,只在 $active 变量为 true 时继续。这一变量之前作为第二个参数传给了 curl_multi_exec() ,代表只要批处理句柄中是否还有活动连接。接着,我们调用 curl_multi_select() ,在活动连接(例如接受服务器响应)出现之前,它都是被“屏蔽”的。这个函数成功执行后,我们又会进入另一个 do-while 循环,继续下一条URL。
还是来看一看怎么把这一功能用到实处吧:


WordPress 连接检查器
想象一下你有一个文章数目庞大的博客,这些文章中包含了大量外部网站链接。一段时间之后,因为这样那样的原因,这些链接中相当数量都失效了。要么是被和谐了,要么是整个站点都被功夫网了...?
我们下面建立一个脚本,分析所有这些链接,找出打不开或者404的网站/网页,并生成一个报告。
请注意,以下并不是一个真正可用的WordPress插件,仅仅是一段独立功能的脚本而已,仅供演示,谢谢。
好,开始吧。首先,从数据库中读取所有这些链接:

php的cURL库介绍

<span>//</span><span> CONFIG</span>
<span>$db_host</span> = 'localhost'<span>;
</span><span>$db_user</span> = 'root'<span>;
</span><span>$db_pass</span> = ''<span>;
</span><span>$db_name</span> = 'wordpress'<span>;
</span><span>$excluded_domains</span> = <span>array</span><span>(
</span>'localhost', 'www.mydomain.com'<span>);
</span><span>$max_connections</span> = 10<span>;
</span><span>//</span><span> 初始化一些变量</span>
<span>$url_list</span> = <span>array</span><span>();
</span><span>$working_urls</span> = <span>array</span><span>();
</span><span>$dead_urls</span> = <span>array</span><span>();
</span><span>$not_found_urls</span> = <span>array</span><span>();
</span><span>$active</span> = <span>null</span><span>;
</span><span>//</span><span> 连到 MySQL</span>
<span>if</span> (!<span>mysql_connect</span>(<span>$db_host</span>, <span>$db_user</span>, <span>$db_pass</span><span>)) {
</span><span>die</span>('Could not connect: ' . <span>mysql_error</span><span>());
}
</span><span>if</span> (!<span>mysql_select_db</span>(<span>$db_name</span><span>)) {
</span><span>die</span>('Could not select db: ' . <span>mysql_error</span><span>());
}
</span><span>//</span><span> 找出所有含有链接的文章</span>
<span>$q</span> = "<span>SELECT post_content FROM wp_posts
WHERE post_content LIKE '%href=%'
AND post_status = 'publish'
AND post_type = 'post'</span>"<span>;
</span><span>$r</span> = <span>mysql_query</span>(<span>$q</span>) or <span>die</span>(<span>mysql_error</span><span>());
</span><span>while</span> (<span>$d</span> = <span>mysql_fetch_assoc</span>(<span>$r</span><span>)) {
</span><span>//</span><span> 用正则匹配链接</span>
<span>if</span> (<span>preg_match_all</span>("!href=\"(.*?)\"!", <span>$d</span>['post_content'], <span>$matches</span><span>)) {
</span><span>foreach</span> (<span>$matches</span>[1] <span>as</span> <span>$url</span><span>) {
</span><span>//</span><span> exclude some domains</span>
<span>$tmp</span> = <span>parse_url</span>(<span>$url</span><span>);
</span><span>if</span> (<span>in_array</span>(<span>$tmp</span>['host'], <span>$excluded_domains</span><span>)) {
</span><span>continue</span><span>;
}
</span><span>//</span><span> store the url</span>
<span>$url_list</span> []= <span>$url</span><span>;
}
}
}
</span><span>//</span><span> 移除重复链接</span>
<span>$url_list</span> = <span>array_values</span>(<span>array_unique</span>(<span>$url_list</span><span>));
</span><span>if</span> (!<span>$url_list</span><span>) {
</span><span>die</span>('No URL to check'<span>);
}</span>

php的cURL库介绍

我们首先配置好数据库,一系列要排除的域名($excluded_domains),以及最大并发连接数($max_connections)。然后,连接数据库,获取文章和包含的链接,把它们收集到一个数组中($url_list)。?

下面的代码有点复杂了,因此我将一小步一小步地详细解释:

php的cURL库介绍

<span>//</span><span> 1. 批处理器</span>
<span>$mh</span> =<span> curl_multi_init();
</span><span>//</span><span> 2. 加入需批量处理的URL</span>
<span>for</span> (<span>$i</span> = 0; <span>$i</span> $max_connections; <span>$i</span>++<span>) {
add_url_to_multi_handle(</span><span>$mh</span>, <span>$url_list</span><span>);
}
</span><span>//</span><span> 3. 初始处理</span>
<span>do</span><span> {
</span><span>$mrc</span> = curl_multi_exec(<span>$mh</span>, <span>$active</span><span>);
} </span><span>while</span> (<span>$mrc</span> ==<span> CURLM_CALL_MULTI_PERFORM);
</span><span>//</span><span> 4. 主循环</span>
<span>while</span> (<span>$active</span> && <span>$mrc</span> ==<span> CURLM_OK) {
</span><span>//</span><span> 5. 有活动连接</span>
<span>if</span> (curl_multi_select(<span>$mh</span>) != -1<span>) {
</span><span>//</span><span> 6. 干活</span>
<span>do</span><span> {
</span><span>$mrc</span> = curl_multi_exec(<span>$mh</span>, <span>$active</span><span>);
} </span><span>while</span> (<span>$mrc</span> ==<span> CURLM_CALL_MULTI_PERFORM);
</span><span>//</span><span> 7. 有信息否?</span>
<span>if</span> (<span>$mhinfo</span> = curl_multi_info_read(<span>$mh</span><span>)) {
</span><span>//</span><span> 意味着该连接正常结束
// 8. 从curl句柄获取信息</span>
<span>$chinfo</span> = curl_getinfo(<span>$mhinfo</span>['handle'<span>]);
</span><span>//</span><span> 9. 死链么?</span>
<span>if</span> (!<span>$chinfo</span>['http_code'<span>]) {
</span><span>$dead_urls</span> []= <span>$chinfo</span>['url'<span>];
</span><span>//</span><span> 10. 404了?</span>
} <span>else</span> <span>if</span> (<span>$chinfo</span>['http_code'] == 404<span>) {
</span><span>$not_found_urls</span> []= <span>$chinfo</span>['url'<span>];
</span><span>//</span><span> 11. 还能用</span>
} <span>else</span><span> {
</span><span>$working_urls</span> []= <span>$chinfo</span>['url'<span>];
}
</span><span>//</span><span> 12. 移除句柄</span>
curl_multi_remove_handle(<span>$mh</span>, <span>$mhinfo</span>['handle'<span>]);
curl_close(</span><span>$mhinfo</span>['handle'<span>]);
</span><span>//</span><span> 13. 加入新URL,干活</span>
<span>if</span> (add_url_to_multi_handle(<span>$mh</span>, <span>$url_list</span><span>)) {
</span><span>do</span><span> {
</span><span>$mrc</span> = curl_multi_exec(<span>$mh</span>, <span>$active</span><span>);
} </span><span>while</span> (<span>$mrc</span> ==<span> CURLM_CALL_MULTI_PERFORM);
}
}
}
}
</span><span>//</span><span> 14. 完了</span>
curl_multi_close(<span>$mh</span><span>);
</span><span>echo</span> "==Dead URLs==\n"<span>;
</span><span>echo</span> <span>implode</span>("\n",<span>$dead_urls</span>) . "\n\n"<span>;
</span><span>echo</span> "==404 URLs==\n"<span>;
</span><span>echo</span> <span>implode</span>("\n",<span>$not_found_urls</span>) . "\n\n"<span>;
</span><span>echo</span> "==Working URLs==\n"<span>;
</span><span>echo</span> <span>implode</span>("\n",<span>$working_urls</span><span>);
</span><span>//</span><span> 15. 向批处理器添加url</span>
<span>function</span> add_url_to_multi_handle(<span>$mh</span>, <span>$url_list</span><span>) {
</span><span>static</span> <span>$index</span> = 0<span>;
</span><span>//</span><span> 如果还剩url没用</span>
<span>if</span> (<span>$url_list</span>[<span>$index</span><span>]) {
</span><span>//</span><span> 新建curl句柄</span>
<span>$ch</span> =<span> curl_init();
</span><span>//</span><span> 配置url</span>
curl_setopt(<span>$ch</span>, CURLOPT_URL, <span>$url_list</span>[<span>$index</span><span>]);
</span><span>//</span><span> 不想输出返回的内容</span>
curl_setopt(<span>$ch</span>, CURLOPT_RETURNTRANSFER, 1<span>);
</span><span>//</span><span> 重定向到哪儿我们就去哪儿</span>
curl_setopt(<span>$ch</span>, CURLOPT_FOLLOWLOCATION, 1<span>);
</span><span>//</span><span> 不需要内容体,能够节约带宽和时间</span>
curl_setopt(<span>$ch</span>, CURLOPT_NOBODY, 1<span>);
</span><span>//</span><span> 加入到批处理器中</span>
curl_multi_add_handle(<span>$mh</span>, <span>$ch</span><span>);
</span><span>//</span><span> 拨一下计数器,下次调用该函数就能添加下一个url了</span>
<span>$index</span>++<span>;
</span><span>return</span> <span>true</span><span>;
} </span><span>else</span><span> {
</span><span>//</span><span> 没有新的URL需要处理了</span>
<span>return</span> <span>false</span><span>;
}
}</span>

php的cURL库介绍

?

下面解释一下以上代码。列表的序号对应着代码注释中的顺序数字。
新建一个批处理器。Created a multi handle.?
稍后我们将创建一个把URL加入批处理器的函数 add_url_to_multi_handle() 。每当这个函数被调用,就有一个新url被加入批处理器。一开始,我们给批处理器添加了10个URL(这一数字由 $max_connections 所决定)。?
运行 curl_multi_exec() 进行初始化工作是必须的,只要它返回 CURLM_CALL_MULTI_PERFORM 就还有事情要做。这么做主要是为了创建连接,它不会等待完整的URL响应。?
只要批处理中还有活动连接主循环就会一直持续。?
curl_multi_select() 会一直等待,直到某个URL查询产生活动连接。?
cURL的活儿又来了,主要是获取响应数据。?
检查各种信息。当一个URL请求完成时,会返回一个数组。?
在返回的数组中有一个 cURL 句柄。我们利用其获取单个cURL请求的相应信息。?
如果这是一个死链或者请求超时,不会返回http状态码。?
如果这个页面找不到了,会返回404状态码。?
其他情况我们都认为这个链接是可用的(当然,你也可以再检查一下500错误之类...)。?
从该批次移除这个cURL句柄,因为它已经没有利用价值了,关了它!?
很好,现在可以另外加一个URL进来了。再一次地,初始化工作又开始进行...?
嗯,该干的都干了。关闭批处理器,生成报告。?
回过头来看给批处理器添加新URL的函数。这个函数每调用一次,静态变量 $index 就递增一次,这样我们才能知道还剩多少URL没处理。?
我把这个脚本在我的博客上跑了一遍(测试需要,有一些错误链接是故意加上的),结果如下:
php的cURL库介绍

共检查约40个URL,只耗费两秒不到。当需要检查更加大量的URL时,其省心省力的效果可想而知!如果你同时打开10个连接,还能再快上10倍!另外,你还可以利用cURL批处理的无隔断特性来处理大量URL请求,而不会阻塞你的Web脚本。


另一些有用的cURL 选项
HTTP 认证
如果某个URL请求需要基于 HTTP 的身份验证,你可以使用下面的代码:

php的cURL库介绍

<span>$url</span> = "http://www.somesite.com/members/"<span>;
</span><span>$ch</span> =<span> curl_init();
curl_setopt(</span><span>$ch</span>, CURLOPT_URL, <span>$url</span><span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_RETURNTRANSFER, 1<span>);
</span><span>//</span><span> 发送用户名和密码</span>
curl_setopt(<span>$ch</span>, CURLOPT_USERPWD, "myusername:mypassword"<span>);
</span><span>//</span><span> 你可以允许其重定向</span>
curl_setopt(<span>$ch</span>, CURLOPT_FOLLOWLOCATION, 1<span>);
</span><span>//</span><span> 下面的选项让 cURL 在重定向后
// 也能发送用户名和密码</span>
curl_setopt(<span>$ch</span>, CURLOPT_UNRESTRICTED_AUTH, 1<span>);
</span><span>$output</span> = curl_exec(<span>$ch</span><span>);
curl_close(</span><span>$ch</span>);

php的cURL库介绍

FTP 上传

PHP 自带有 FTP 类库, 但你也能用 cURL:

php的cURL库介绍

<span>//</span><span> 开一个文件指针</span>
<span>$file</span> = <span>fopen</span>("/path/to/file", "r"<span>);
</span><span>//</span><span> url里包含了大部分所需信息</span>
<span>$url</span> = "ftp://username:password@mydomain.com:21/path/to/new/file"<span>;
</span><span>$ch</span> =<span> curl_init();
curl_setopt(</span><span>$ch</span>, CURLOPT_URL, <span>$url</span><span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_RETURNTRANSFER, 1<span>);
</span><span>//</span><span> 上传相关的选项</span>
curl_setopt(<span>$ch</span>, CURLOPT_UPLOAD, 1<span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_INFILE, <span>$fp</span><span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_INFILESIZE, <span>filesize</span>("/path/to/file"<span>));
</span><span>//</span><span> 是否开启ASCII模式 (上传文本文件时有用)</span>
curl_setopt(<span>$ch</span>, CURLOPT_FTPASCII, 1<span>);
</span><span>$output</span> = curl_exec(<span>$ch</span><span>);
curl_close(</span><span>$ch</span>);

php的cURL库介绍

?

FQ术
你可以用代理发起cURL请求:

php的cURL库介绍

<span>$ch</span> =<span> curl_init();
curl_setopt(</span><span>$ch</span>, CURLOPT_URL,'http://www.example.com'<span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_RETURNTRANSFER, 1<span>);
</span><span>//</span><span> 指定代理地址</span>
curl_setopt(<span>$ch</span>, CURLOPT_PROXY, '11.11.11.11:8080'<span>);
</span><span>//</span><span> 如果需要的话,提供用户名和密码</span>
curl_setopt(<span>$ch</span>, CURLOPT_PROXYUSERPWD,'user:pass'<span>);
</span><span>$output</span> = curl_exec(<span>$ch</span><span>);
curl_close (</span><span>$ch</span>);

php的cURL库介绍

?

回调函数
可以在一个URL请求过程中,让cURL调用某指定的回调函数。例如,在内容或者响应下载的过程中立刻开始利用数据,而不用等到完全下载完。

php的cURL库介绍

<span>$ch</span> =<span> curl_init();
curl_setopt(</span><span>$ch</span>, CURLOPT_URL,'http://api.doucube.com'<span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_WRITEFUNCTION,"progress_function"<span>);
curl_exec(</span><span>$ch</span><span>);
curl_close (</span><span>$ch</span><span>);
</span><span>function</span> progress_function(<span>$ch</span>,<span>$str</span><span>) {
</span><span>echo</span> <span>$str</span><span>;
</span><span>return</span> <span>strlen</span>(<span>$str</span><span>);
}</span>

php的cURL库介绍

?

这个回调函数必须返回字串的长度,不然此功能将无法正常使用。
在URL响应接收的过程中,只要收到一个数据包,这个函数就会被调用。

POST数据
向某个网页POST数据。假设我们有一个处理表单的网址http://www.example.com/sendSMS.php,其可以接受两个表单域,一个是电话号码,一个是短信内容。

php的cURL库介绍

﹤?<span>php
</span><span>$phoneNumber</span> = '13912345678'<span>;
</span><span>$message</span> = 'This message was generated by curl and php'<span>;
</span><span>$curlPost</span> = 'pNUMBER=' . <span>urlencode</span>(<span>$phoneNumber</span>) . '&MESSAGE=' . <span>urlencode</span>(<span>$message</span>) . '&SUBMIT=Send'<span>;
</span><span>$ch</span> =<span> curl_init();
curl_setopt(</span><span>$ch</span>, CURLOPT_URL, 'http://www.example.com/sendSMS.php'<span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_HEADER, 1<span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_RETURNTRANSFER, 1<span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_POST, 1<span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_POSTFIELDS, <span>$curlPost</span><span>);
</span><span>$data</span> =<span> curl_exec();
curl_close(</span><span>$ch</span><span>);
</span>?﹥

php的cURL库介绍

从上面的程序我们可以看到,使用CURLOPT_POST设置HTTP协议的POST方法,而不是GET方法,然后以CURLOPT_POSTFIELDS设置POST的数据。

代理服务器
下面是一个如何使用代理服务器的示例。请注意其中高亮的代码,代码很简单,我就不用多说了。

php的cURL库介绍

﹤?<span>php 
</span><span>$ch</span> =<span> curl_init();
curl_setopt(</span><span>$ch</span>, CURLOPT_URL, 'http://www.example.com'<span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_HEADER, 1<span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_RETURNTRANSFER, 1<span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_HTTPPROXYTUNNEL, 1<span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_PROXY, 'fakeproxy.com:1080'<span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_PROXYUSERPWD, 'user:password'<span>);
</span><span>$data</span> =<span> curl_exec();
curl_close(</span><span>$ch</span><span>);
</span>?﹥

php的cURL库介绍

?

SSL和Cookie
关于SSL也就是HTTPS协议,你只需要把CURLOPT_URL连接中的http://变成https://就可以了。当然,还有一个参数叫CURLOPT_SSL_VERIFYHOST可以设置为验证站点。
关于Cookie,你需要了解下面三个参数:
CURLOPT_COOKIE,在当面的会话中设置一个cookie
CURLOPT_COOKIEJAR,当会话结束的时候保存一个Cookie
CURLOPT_COOKIEFILE,Cookie的文件。

HTTP服务器认证
最后,我们来看一看HTTP服务器认证的情况。

php的cURL库介绍

﹤?<span>php 
</span><span>$ch</span> =<span> curl_init();
curl_setopt(</span><span>$ch</span>, CURLOPT_URL, 'http://www.example.com'<span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_RETURNTRANSFER, 1<span>);
curl_setopt(</span><span>$ch</span>, CURLOPT_HTTPAUTH,<span> CURLAUTH_BASIC);
curl_setopt(CURLOPT_USERPWD</span>, '[username]:[password]'<span>)
</span><span>$data</span> =<span> curl_exec();
curl_close(</span><span>$ch</span><span>);
</span>?﹥

php的cURL库介绍

?

关于其它更多的内容,请参看相关的cURL手册。

小结
今天我们一起学习了cURL库的强大功能和灵活的扩展性。希望你喜欢。下一次要发起URL请求时,考虑下cURL吧!

?

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn