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'].'秒';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.'?'.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!

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

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.

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.

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

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.

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.

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.

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.


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

WebStorm Mac version
Useful JavaScript development tools

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
Small size, syntax highlighting, does not support code prompt function

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
Recommended: Win version, supports code prompts!
