Home  >  Article  >  Backend Development  >  Detailed explanation of using CURL in PHP

Detailed explanation of using CURL in PHP

韦小宝
韦小宝Original
2018-02-10 10:52:043052browse

CURL is a very powerful open source library that supports many protocols, including HTTP, FTP, TELNET, etc. We use it to send HTTP requests. The benefit it brings us is that we can set different HTTP protocol parameters through flexible options and supports HTTPS. CURL can automatically choose whether to encrypt the sent content based on whether the URL prefix is ​​"HTTP" or "HTTPS".

Basic process of using CURL to send a request

Using CURL's PHP extension to complete sending an HTTP request generally has the following steps:

Initialize the connection handle;

Set CURL options;

Execute and get the results;

Release the VURL connection handle.

The following program fragment is a typical process of sending HTTP using CURL

// 1. 初始化
 $ch = curl_init(); // 2. 设置选项,包括URL
 curl_setopt($ch,CURLOPT_URL,"http://www.devdo.net");
 curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
 curl_setopt($ch,CURLOPT_HEADER,0); // 3. 执行并获取HTML文档内容
 $output = curl_exec($ch); if($output === FALSE ){ echo "CURL Error:".curl_error($ch);
 } // 4. 释放curl句柄
 curl_close($ch);

Four functions are used in the above code

  • curl_init() and curl_close () are to initialize the CURL connection and close the CURL connection respectively, which are relatively simple.

  • curl_exec() executes a CURL request. If no error occurs, the return of this function is the data returned by the corresponding URL, indicating satisfaction with string; if an error occurs , the function returns FALSE. It should be noted that the equal sign is used to determine whether the output is FALSE. This is to distinguish between returning an empty string and an error.

  • The most important function in the CURL function library is curl_setopt(), which can customize HTTP requests by setting options defined by the CURL function library. Three important options are used in the above code snippet:

##         1. CURLOPT_URL specifies the URL of the request;

      2. CURLOPT_RETURNTRANSFER is set to 1 to indicate curl_exec to be executed later. The return of the function is the return string of the URL, instead of directing the return string to the standard output and returning TRUE;

CURL has many options. You can go to PHP’s official website (http://www.php.net/manual/en/function.curl-setopt.php) to view a list of all options supported by CURL. .

Get the output information of the CURL request

After the curl_exec() function is executed, you can use the curl_getinfo() function to obtain the relevant information output of the CURL request. The sample code is as follows:

curl_exec($ch);
$info = curl_getinfo($sh);
echo ' 获取 '.$info['url'].'耗时'.$info['total_time'].'秒';

In the above code, curl_getinfo returns an associative array, containing the following data:

url: network address.
  • content_type: Content encoding.
  • http_code:
  • HTTP status code
  • .

    header_size: The size of the header.
  • request_size: The size of the request.
  • filetime: The time when the file was created.
  • ssl_verify_result: SSL verification result.
  • redirect_count: Jump count.
  • total_time: Total time taken.
  • namelookup_time: DNS query takes time.
  • connect_time: Time spent waiting for connection.
  • pretransfer_time: Pretransfer preparation time.
  • size_uplpad: The size of the uploaded data.
  • size_download: The size of the downloaded data.
  • speed_download: Download speed.
  • speed_upload: Upload speed.
  • download_content_length: The length of the download content.
  • upload_content_length: The length of the uploaded content.
  • starttransfer_time: Timetable to start transfer.
  • redirect_time: redirection takes time.

curl_getinfo()函数还有一个可选择参数$opt,通过这个参数可以设置一些常量,对应到上术这个字段,如果设置了第二个参数,那么返回的只有指定的信息。例如设置$opt为CURLINFO_TOTAL_TIME,则curl_getinfo()函数只返回total_time,即总传输消耗的时间,在只需要关注某些传输信息时,设置$opt参数很有意义。

使用CURL发送GET请求

如何使用CURL来发送GET请求,发送GET请求的关键是拼装格式正确的URL。请求地址和GET数据由一个“?”分割,然后GET变量的名称和值用“=”分隔,各个GET名称和值由“&”连接。PHP为我们提供了一个函数专门用来拼装GET请求和数据部分——http_build_query,该函数接受一个关联数组,返回由该关联数据描述的GET请求字符串。使用这个函数,结合CURL发送HTTP请求的一般流程,我们封闭了一个发送GET请求的函数——doCurlGetRequest,具体代码如下:

**
 *@desc 封闭curl的调用接口,get的请求方式。
*/
function doCurlGetRequest($url,$data,$timeout = 5){
 if($curl == "" || $timeout <= 0){
 return false;
 }
 $url = $url.&#39;?&#39;.http_bulid_query($data);
 $con = curl_init((string)$url);
 curl_setopt($con, CURLOPT_HEADER, false);
 curl_setopt($con, CURLOPT_RETURNTRANSFER,true);
 curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);
 
 return curl_exec($con);
}

这个函数把使用http_build_query 拼装好的带GET参数的URL传给curl_init函数,然后使用CURL发送HTTP请求。

使用CURL发送POST请求

可以使用CURL提供的选项CURLOPT_POSTFIELDS,设置该选项为POST字符串数据就可以把请求放在正文中。同样我们实现了一个发送POST请求的函数——doCurlPostRequest,代码如下:

/**
** @desc 封装 curl 的调用接口,post的请求方式
**/
function doCurlPostRequest($url,$requestString,$timeout = 5){
 if($url == &#39;&#39; || $requestString == &#39;&#39; || $timeout <=0){
 return false;
 }
 $con = curl_init((string)$url);
 curl_setopt($con, CURLOPT_HEADER, false);
 curl_setopt($con, CURLOPT_POSTFIELDS, $requestString);
 curl_setopt($con, CURLOPT_POST,true);
 curl_setopt($con, CURLOPT_RETURNTRANSFER,true);
 curl_setopt($con, CURLOPT_TIMEOUT,(int)$timeout);
 return curl_exec($con); 
}

上面代码中除了设置CURLOPT_POSTFIELDS外,我们还设置了CURL_POST为true,标识这个请求是一个POST请求。在POST请求中也是可以传输GET数据的,只需要在URL中拼装GET请求数据即可秀。

相关文件

php实现curl上传下载https登陆

本文主要和大家介绍了php curl上传、下载、https登陆实现代码,需要的朋友可以参考下......

PHP功能强大的CURL POST类

本文主要为大家详细介绍了功能强大的PHP POST提交数据类,代码简洁且具有一定的参......

PHP学习CURL之爬虫实例

很多时候我们需要批量抓取一些网站的资源,这个时候就需要用到爬虫......

The above is the detailed content of Detailed explanation of using CURL in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn