The content of this article introduces a detailed explanation of the use of CURL in PHP. Now I share it with you. Friends in need can refer to it
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".
The basic process of sending a request using CURL
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 initialization respectively CURL connection and closing CURL connection are relatively simple.
- curl_exec() executes a CURL request. If no error occurs, the function returns the data returned by the corresponding URL, indicating satisfaction as a 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:
- CURLOPT_URL specifies the requested URL;
- CURLOPT_RETURNTRANSFER is set to 1. The return of the curl_exec function executed later is the return string of the URL, instead of directing the return string to the standard output and returning TRUE;
- CURLLOPT_HEADER is set to 0 to indicate that no HTTP header is returned department information.
curl_exec($ch);$info = curl_getinfo($sh);echo ' 获取 '.$info['url'].'耗时'.$info['total_time'].'秒';
上述代码中curl_getinfo返回的是一个关联数组,包含以下数据:
url:网络地址。
content_type:内容编码。
http_code:HTTP状态码。
header_size:header的大小。
request_size:请求的大小。
filetime:文件创建的时间。
ssl_verify_result:SSL验证结果。
redirect_count:跳转计数。
total_time:总耗时。
namelookup_time:DNS查询耗时。
connect_time:等待连接耗时。
pretransfer_time:传输前准备耗时。
size_uplpad:上传数据的大小。
size_download:下载数据的大小。
speed_download:下载速度。
speed_upload:上传速度。
download_content_length:下载内容的长度。
upload_content_length:上传内容的长度。
starttransfer_time:开始传输的时间表。
redirect_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 <p class="cnblogs_code_toolbar" style="margin:5px 0px 0px;padding:0px;"><span class="cnblogs_code_copy" style="margin:0px;padding:0px 5px 0px 0px;line-height:1.5;"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/153/291/88596a8d53f6dae6de7dddd6f6df4237-0.gif?x-oss-process=image/resize,p_40" class="lazy" alt="Detailed explanation of using CURL in PHP"></span></p><p style="max-width:90%">这个函数把使用http_build_query 拼装好的带GET参数的URL传给curl_init函数,然后使用CURL发送HTTP请求。</p><h2 id="使用CURL发送POST请求">使用CURL发送POST请求</h2><p style="margin:10px auto;color:rgb(51,51,51);font-family:Verdana, Arial, Helvetica, sans-serif;font-size:14px;background-color:rgb(255,255,255);">可以使用CURL提供的选项CURLOPT_POSTFIELDS,设置该选项为POST字符串数据就可以把请求放在正文中。同样我们实现了一个发送POST请求的函数——doCurlPostRequest,代码如下:</p><p class="cnblogs_code" style="margin:5px 0px;padding:5px;background-color:rgb(245,245,245);border:1px solid rgb(204,204,204);color:rgb(0,0,0);font-family:'Courier New';font-size:12px;"><br></p><p class="cnblogs_code_toolbar" style="margin:5px 0px 0px;padding:0px;"><span class="cnblogs_code_copy" style="margin:0px;padding:0px 5px 0px 0px;line-height:1.5;"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/153/291/88596a8d53f6dae6de7dddd6f6df4237-0.gif?x-oss-process=image/resize,p_40" class="lazy" alt="Detailed explanation of using CURL in PHP"></span></p><pre style="max-width:90%"Courier New';" class="brush:php;toolbar:false;">/** ** @desc 封装 curl 的调用接口,post的请求方式 **/function doCurlPostRequest($url,$requestString,$timeout = 5){ if($url == '' || $requestString == '' || $timeout <p class="cnblogs_code_toolbar" style="margin:5px 0px 0px;padding:0px;"><span class="cnblogs_code_copy" style="margin:0px;padding:0px 5px 0px 0px;line-height:1.5;"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/153/291/88596a8d53f6dae6de7dddd6f6df4237-0.gif?x-oss-process=image/resize,p_40" class="lazy" alt="Detailed explanation of using CURL in PHP"></span></p><p style="max-width:90%">上面代码中除了设置CURLOPT_POSTFIELDS外,我们还设置了CURL_POST为true,标识这个请求是一个POST请求。在POST请求中也是可以传输GET数据的,只需要在URL中拼装GET请求数据即可秀</p><p style="margin: 10px auto; color: rgb(51, 51, 51); font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 14px; background-color: rgb(255, 255, 255);">相关推荐:</p><p style="margin: 10px auto; color: rgb(51, 51, 51); font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 14px; background-color: rgb(255, 255, 255);"><a href="http://www.php.cn/php-weizijiaocheng-392124.html" target="_self">PHP中如何利用CURL实现GET和POST请求</a></p><p style="margin: 10px auto; color: rgb(51, 51, 51); font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 14px; background-color: rgb(255, 255, 255);"><a href="http://www.php.cn/php-weizijiaocheng-392115.html" target="_self">PHP利用CURL将他人服务器图片上传到自己的图片云空间</a></p><p style="margin: 10px auto; color: rgb(51, 51, 51); font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 14px; background-color: rgb(255, 255, 255);"><a href="http://www.php.cn/php-weizijiaocheng-392063.html" target="_self">PHP中的curl 函数并发实现减少后端访问时间</a></p>
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!

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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),

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.