一切来源于深圳翻译Why cURL?
It's true that there are other ways of fetching the contents of a web page. Many times, mostly due to laziness, I have just used simple PHP functions instead of cURL:
为什么要用 cURL?
是的,我们可以通过其他办法获取网页内容。大多数时候,我因为想偷懒,都直接用简单的PHP函数:view plaincopy to clipboardprint?
However they have virtually no flexibility and lack sufficient error handling. Also, there are certain tasks that you simply can not do, like dealing with cookies, authentication, form posts, file uploads etc.
不过,这种做法缺乏灵活性和有效的错误处理。而且,你也不能用它完成一些高难度任务——比如处理coockies、验证、表单提交、文件上传等等。
cURL is a powerful library that supports many different protocols, options, and provides detailed information about the URL requests.
cURL 是一种功能强大的库,支持很多不同的协议、选项,能提供 URL 请求相关的各种细节信息。
Basic Structure基本结构
Before we move on to more complicated examples, let's review the basic structure of a cURL request in PHP. There are four main steps:
在学习更为复杂的功能之前,先来看一下在PHP中建立cURL请求的基本步骤:
Initialize 
Set Options 
Execute and Fetch Result 
Free up the cURL handle 
初始化 
设置变量 
执行并获取结果 
释放cURL句柄 
view plaincopy to clipboardprint?
4. free up the curl handlecurl_close($ch);Step #2 (i.e. curl_setopt() calls) is going to be a big part of this article, because that is where all the magic happens. There is a long list of cURL options that can be set, which can configure the URL request in detail. It might be difficult to go through the whole list and digest it all at once. So today, we are just going to use some of the more common and useful options in various code examples.
4. 释放curl句柄curl_close($ch);第二步(也就是 curl_setopt() )最为重要,一切玄妙均在此。有一长串cURL参数可供设置,它们能指定URL请求的各个细节。要一次性全部看完并理解可能比较困难,所以今天我们只试一下那些更常用也更有用的选项。Checking for ErrorsOptionally, you can also add error checking:
检查错误你可以加一段检查错误的语句(虽然这并不是必需的):view plaincopy to clipboardprint?
Please note that we need to use "=== FALSE" for comparison instead of "== FALSE". Because we need to distinguish between empty output vs. the boolean value FALSE, which indicates an error.
请注意,比较的时候我们用的是“=== FALSE”,而非“== FALSE”。因为我们得区分 空输出 和 布尔值FALSE,后者才是真正的错误。Getting InformationAnother optional step is to get information about the cURL request, after it has been executed.
获取信息这是另一个可选的设置项,能够在cURL执行后获取这一请求的有关信息:view plaincopy to clipboardprint?
"url" 
"content_type" 
"http_code" 
"header_size" 
"request_size" 
"filetime" 
"ssl_verify_result" 
"redirect_count" 
"total_time" 
"namelookup_time" 
"connect_time" 
"pretransfer_time" 
"size_upload" 
"size_download" 
"speed_download" 
"speed_upload" 
"download_content_length" 
"upload_content_length" 
"starttransfer_time" 
"redirect_time" 
“url” //资源网络地址 
“content_type” //内容编码 
“http_code” //HTTP状态码 
“header_size” //header的大小 
“request_size” //请求的大小 
“filetime” //文件创建时间 
“ssl_verify_result” //SSL验证结果 
“redirect_count” //跳转技术 
“total_time” //总耗时 
“namelookup_time” //DNS查询耗时 
“connect_time” //等待连接耗时 
“pretransfer_time” //传输前准备耗时 
“size_upload” //上传数据的大小 
“size_download” //下载数据的大小 
“speed_download” //下载速度 
“speed_upload” //上传速度 
“download_content_length”//下载内容的长度 
“upload_content_length” //上传内容的长度 
“starttransfer_time” //开始传输的时间 
“redirect_time”//重定向耗时 Detect Redirection Based on Browser
In this first example, we will write a script that can detect URL redirections based on different browser settings. For example, some websites redirect cellphone browsers, or even surfers from different countries.
基于浏览器的重定向在第一个例子中,我们将提供一段用于侦测服务器是否有基于浏览器的重定向的代码。例如,有些网站会根据是否是手机浏览器甚至用户来自哪个国家来重定向网页。We are going to be using the CURLOPT_HTTPHEADER option to set our outgoing HTTP Headers including the user agent string and the accepted languages. Finally we will check to see if these websites are trying to redirect us to different URLs.
我们利用 CURLOPT_HTTPHEADER 选项来设定我们发送出的HTTP请求头信息(http headers),包括user agent信息和默认语言。然后我们来看看这些特定网站是否会把我们重定向到不同的URL。view plaincopy to clipboardprint?
Multi cURL
One of the more advanced features of cURL is the ability to create a "multi" cURL handle. This allows you to open connections to multiple URLs simultaneously and asynchronously.
首先,我们建立一组需要测试的URL,接着指定一组需要测试的浏览器信息。最后通过循环测试各种URL和浏览器匹配可能产生的情况。还是来看一看怎么把这一功能用到实处吧:WordPress 连接检查器
想象一下你有一个文章数目庞大的博客,这些文章中包含了大量外部网站链接。一段时间之后,因为这样那样的原因,这些链接中相当数量都失效了。要么是被和谐了,要么是整个站点都被功夫网了...我们下面建立一个脚本,分析所有这些链接,找出打不开或者404的网站/网页,并生成一个报告。请注意,以下并不是一个真正可用的WordPress插件,仅仅是一段独立功能的脚本而已,仅供演示,谢谢。好,开始吧。首先,从数据库中读取所有这些链接:// CONFIG$db_host = 'localhost';$db_user = 'root';$db_pass = '';$db_name = 'wordpress';$excluded_domains = array( 'localhost', 'www.mydomain.com');$max_connections = 10;// 初始化一些变量$url_list = array();$working_urls = array();$dead_urls = array();$not_found_urls = array();$active = null;// 连到 MySQLif (!mysql_connect($db_host, $db_user, $db_pass)) { die('Could not connect: ' . mysql_error());}if (!mysql_select_db($db_name)) { die('Could not select db: ' . mysql_error());}// 找出所有含有链接的文章$q = "SELECT post_content FROM wp_posts WHERE post_content LIKE '%href=%' AND post_status = 'publish' AND post_type = 'post'";$r = mysql_query($q) or die(mysql_error());while ($d = mysql_fetch_assoc($r)) { // 用正则匹配链接 if (preg_match_all("!href=\"(.*?)\"!", $d['post_content'], $matches)) { foreach ($matches[1] as $url) { // exclude some domains $tmp = parse_url($url); if (in_array($tmp['host'], $excluded_domains)) { continue; } // store the url $url_list []= $url; } }}// 移除重复链接$url_list = array_values(array_unique($url_list));if (!$url_list) { die('No URL to check');}我们首先配置好数据库,一系列要排除的域名($excluded_domains),以及最大并发连接数($max_connections)。然后,连接数据库,获取文章和包含的链接,把它们收集到一个数组中($url_list)。