PHP语言中php curl的几种应用方式 - Go语言中文社区

PHP语言中php curl的几种应用方式


我们通过对PHP开发基础入门这一专题的学习可以了解到,PHP语言的一些具体概念的实际应用。今天我们向大家介绍的是在PHP中的php curl的几种使用方式,希望对有需要的朋友有所帮助。

1. php curl的默认调用方法,get方式访问url
  1. ....     
  2.     $ch = curl_init();     
  3.     curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//设置http头     
  4.     curl_setopt($ch, CURLOPT_ENCODING, "gzip" ); 
    //设置为客户端支持gzip压缩     
  5.     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30 ); 
    //设置连接等待时间     
  6.     curl_setopt($ch, CURLOPT_URL, $url );     
  7.     curl_exec( $ch );     
  8.     if ($error = curl_error($ch) ) {     
  9.         //出错处理     
  10.         return -1;     
  11.     }     
  12.     fclose($fp);       
  13.     
  14.     $curl_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    //获取http返回值     
  15.     if( $curl_code == 200 ) {     
  16.         //正常访问url     
  17.     }     
  18.     //异常     
  19. ....    

2. 设置http header支持php curl访问lighttpd服务器

  1. $header[]= 'Expect:';  

3. 设置curl,只获取http header,不获取body:

  1. curl_setopt($ch, CURLOPT_HEADER, 1);       
  2. curl_setopt($ch, CURLOPT_NOBODY, 1);      

或者只获取body:

  1. curl_setopt($ch, CURLOPT_HEADER, 0);   
    // make sure we get the body     
  2. curl_setopt($ch, CURLOPT_NOBODY, 0);     

4. 访问虚拟主机,需设置Host

  1. $header[]= 'Host: '.$host;   

5. 使用post, put, delete等REStful方式访问url

  1. post:   
  2.  
  3.   curl_setopt($ch, CURLOPT_POST, 1 );   
  4.  
  5. put, delete:   
  6.  
  7.   curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");  
    //或者PUT,需要服务器支持这些方法。  

6. php curl保存下载内容为文件

  1. curl_setopt($ch, CURLOPT_FILE, $fp);  
【责任编辑:曹凯 TEL:(010)68476606】

点赞 0
版权声明:本文来源51CTO,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:http://developer.51cto.com/art/200911/164435.htm
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-05-16 12:31:18
  • 阅读 ( 1337 )
  • 分类:Go应用

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢