curl是利用URL语法在命令行方式下工作的开源文件传输工具,使用非常广泛。php也通过由 Daniel Stenberg开发的libcurl扩展库对curl提供支持。libcurl支持的协议很多,比如:http,https,ftp,gopher,telnet,dict,file,ldap。并且提供了相关的很多强大功能,在php4.0.2后,引入了很多功能函数。通过这篇文章libcurl进行一个总结。
一、安装与配置
在使用libcurl前你需要安装libcurl包,需要libcurl7.0.2 beta以上版本。
php4.2.3 需要 libcurl 7.9.0以上; php 4.3.0 需要 libcurl 7.9.8以上 ; php5.0 以上 需要libcurl 7.10.5 以上。
为了使用libcurl,你必须在编译php时就打开了–with-curl=DIR配置,其中DIR是包含lib和include的路径,在includ中有一个名为curl的文件夹包含eash.h 和curl.h文件。在lib文件夹中有一个名为libcurl.a 的库文件。
二、资源类型
扩展定义了两种资源类型: 一个是cURL句柄 ,一个是cURL multi 句柄。
三、预定义常量
libcurl扩展定义了很多常量,只有在PHP已经编译此扩展的前提下才能使用,他们将在 curl_setopt() ,curl_multi_setopt() ,curl_getinfo() 中使用。
四、简单原理
一单编译php支持libcurl扩展后,就可以使用cURL函数了。其工作大致分为四步:
简单示例代码如下:
$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);
?>
五、cURL 函数
curl_init ([ string $url = NULL ] )
初始化一个session并返回一个cURL 句柄以方便下面的函数使用。
参数:url 如果不设置,可以在 curl_setopt() 中通过常量CURLOPT_URL 设置。
curl_setopt ( resource ch,int option , mixed $value )
设置cURL
ch为 curl_init()返回的句柄 , option为预设置的常量,value,为常量的值
class CurlLib
{
static public function http($url, $userpass = "", $postdata = false, $timeout = false, $cookies = "")
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if( !empty($cookies) )
curl_setopt($ch, CURLOPT_COOKIE, $cookies);
if( $timeout !== false && is_numeric($timeout))
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
if( !empty($userpass))
curl_setopt($ch, CURLOPT_USERPWD, $userpass);
if($postdata !==false)
{
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
}
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($code == 200)
return $response;
else
{
return array('code'=>$code, 'response'=>$response);
}
}
}