PHP函数库里面,提到CURL,恐怕很多人都会翘起大拇指吧,确实,这个函数库太牛叉了
CURL其实是调用的CURL的lib,随着PHP版本的升高,curl所需的lib版本也随之提高。
关于CURL所必须的类库和安装说明,手册上有详细介绍:
XML/HTML代码
- Requirements
-
- In order to use PHP's cURL functions you need to install the libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.
-
- Installation
-
- To use PHP's cURL support you must also compile PHP --with-curl[=DIR] where DIR is the location of the directory containing the lib and include directories. In the "include" directory there should be a folder named "curl" which should contain the easy.h and curl.h files. There should be a file named libcurl.a located in the "lib" directory. Beginning with PHP 4.3.0 you can configure PHP to use cURL for URL streams --with-curlwrappers.
-
- Note to Win32 Users: In order to enable this module on a Windows environment, libeay32.dll and ssleay32.dll must be present in your PATH.
- You don't need libcurl.dll from the cURL site.
然后在使用的时候也很方便,只需要初始化一下,设置一下postfields或者GET啥啥的,最后exec一下就行了。关键是别忘了close.
例子代码如下:
PHP代码
- $ch = curl_init("http://www.example.com/");
- $fp = fopen("example_homepage.txt", "w");
-
- curl_setopt($ch, CURLOPT_FILE, $fp);
- curl_setopt($ch, CURLOPT_HEADER, 0);
-
- curl_exec($ch);
- curl_close($ch);
- fclose($fp);
以上例子代码有点特殊,是因为他把网页内容进行了下载,同时生成一个文件。这是默认调用GET的方法。
其实,CURL更多的是用来处理POST数据、上传文件等功能
例子如下:
PHP代码
- <?
-
-
-
-
-
-
- $url = 'http://www.ericgiguere.com/tools/http-header-viewer.html';
-
-
- function disguise_curl($url)
- {
- $curl = curl_init();
-
-
-
- $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
- $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
- $header[] = "Cache-Control: max-age=0";
- $header[] = "Connection: keep-alive";
- $header[] = "Keep-Alive: 300";
- $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
- $header[] = "Accept-Language: en-us,en;q=0.5";
- $header[] = "Pragma: ";
-
- curl_setopt($curl, CURLOPT_URL, $url);
- curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
- curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
- curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');
- curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
- curl_setopt($curl, CURLOPT_AUTOREFERER, true);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($curl, CURLOPT_TIMEOUT, 10);
-
- $html = curl_exec($curl);
- curl_close($curl);
-
- return $html;
- }
-
-
- $text = disguise_curl($url);
- echo $text;
- ?>
上面是一个比较完整的实现。特别需要注意的是header头部的发送,最初看手册的时候,我一以为CURLOPT_HTTPHEADER所需的数组是键值对应的,即:
PHP代码
- $header = array('Keep-Alive'=>'300');
现实的残酷告诉我,不应该这么用,而是象上面的例子那样,每条header为数组的一个记录。
切记切记啊