Detailed explanation of using CURL in PHP
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:
curl_exec($ch); $info = curl_getinfo($sh); echo ' 获取 '.$info['url'].'耗时'.$info['total_time'].'秒';
- 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.'?'.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 == '' || $requestString == '' || $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 POST提交数据类,代码简洁且具有一定的参......
很多时候我们需要批量抓取一些网站的资源,这个时候就需要用到爬虫......
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
