search
HomeBackend DevelopmentPHP TutorialDetailed explanation of using CURL in PHP

Detailed explanation of using CURL in PHP

Feb 10, 2018 am 10:52 AM
curlphpexplain

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
Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Give an example of how to store a user's name in a PHP session.Give an example of how to store a user's name in a PHP session.Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!