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

开发 后端
今天向大家介绍的是在PHP中php curl的几种应用方式,包括:php curl的默认调用方法,get方式访问url;设置http header支持php curl访问lighttpd服务器;设置curl,只获取http header,不获取body等等。

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

#t#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);  
责任编辑:曹凯 来源: javaeye社区
相关推荐

2019-08-28 09:04:02

Go语言Python操作系统

2011-05-25 13:22:05

PHPJSON

2009-11-23 11:03:12

php_curl库

2011-05-13 16:30:25

PHP

2011-05-19 14:00:51

PHP单引号双引号

2009-12-25 15:02:01

php扩展cURL

2009-12-02 18:03:00

PHP cURL

2011-05-30 13:15:05

PHP

2009-11-30 16:24:24

PHP脚本

2009-11-25 14:31:43

PHP自然语言倒序

2009-01-15 13:26:14

PHPWeb开发ASP.NET

2016-08-11 09:48:53

2021-04-28 09:02:48

Golang语言Context

2009-11-26 14:23:10

PHP正则模式修正符

2011-05-20 10:37:04

PHP

2011-05-07 08:35:22

PHP

2009-12-10 17:02:50

PHP站点性能

2009-09-09 11:24:46

PHP实现MVC

2009-12-02 20:02:18

PHP实现页面跳转

2009-12-02 10:01:04

PHP乱码问题
点赞
收藏

51CTO技术栈公众号