站长论坛

标题: php curl的几种用法 [打印本页]

作者: superadmin    时间: 2009-8-1 17:23
标题: php curl的几种用法
总结一下项目中用到curl的几种方式
1. php curl的默认调用方法,get方式访问url

....   
    $ch = curl_init();   
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);    //设置http头   
    curl_setopt($ch, CURLOPT_ENCODING, "gzip" );         //设置为客户端支持gzip压缩   
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30 );  //设置连接等待时间   
    curl_setopt($ch, CURLOPT_URL, $url );   
    curl_exec( $ch );   
    if ($error = curl_error($ch) ) {   
        //出错处理   
        return -1;   
    }   
    fclose($fp);     
  
    $curl_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);        //获取http返回值   
    if( $curl_code == 200 ) {   
        //正常访问url   
    }   
    //异常   
....  

2. 设置http header支持curl访问lighttpd服务器
Java代码
$header[]= 'Expect:';     

$header[]= 'Expect:';   
3. 设置curl,只获取http header,不获取body:
Java代码
curl_setopt($ch, CURLOPT_HEADER, 1);     
curl_setopt($ch, CURLOPT_NOBODY, 1);     

curl_setopt($ch, CURLOPT_HEADER, 1);  
curl_setopt($ch, CURLOPT_NOBODY, 1);   
或者只获取body:
Java代码
curl_setopt($ch, CURLOPT_HEADER, 0);   // make sure we get the body   
curl_setopt($ch, CURLOPT_NOBODY, 0);   

    curl_setopt($ch, CURLOPT_HEADER, 0);   // make sure we get the body
    curl_setopt($ch, CURLOPT_NOBODY, 0);
4. 访问虚拟主机,需设置Host
$header[]= 'Host: '.$host;  
5. 使用post, put, delete等REStful方式访问url
post:
    curl_setopt($ch, CURLOPT_POST, 1 );
put, delete:
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");  //或者PUT,需要服务器支持这些方法。
6. 保存下载内容为文件
    curl_setopt($ch, CURLOPT_FILE, $fp);
作者: superadmin    时间: 2009-8-1 17:23
要想简单方便,建议使用pear里的HTTP_Request
我自己感觉比直接使用更方便。

HTTP_Request是把curl又封装了一下。




欢迎光临 站长论坛 (http://www.tzlink.com/bbs/) Powered by Discuz! X3.2