cURL request and sample study notes in PHP_PHP tutorial
cURL is a very powerful function in PHP. It can imitate various user requests, such as imitating user login, sending PHP cookies and other operations. Let me sort out some related methods and share them with you
Remarks:To use the curl_init function, this php extension must be turned on.
1. Open php.ini and enable extension=php_curl.dll
2. Check which directory the extension_dir value of php.ini is, and check whether there is php_curl.dll. If not, please download php_curl.dll, and then copy libeay32.dll and ssleay32.dll in the php directory to c:/windows/system32 .
Recently, in the process of learning the API interface of Tencent Open Platform, I saw a very powerful PHP library-cURL. It is a file transfer tool that uses URL syntax to work in command line mode. This article was translated directly by the blogger from a foreign blog. The original address is: http://codular.com/curl-with-php. This article is very basic, but the organization is very clear, and the knowledge is relatively systematic and comprehensive, so I turned it over and saved it! (Some of the titles below are superfluous by bloggers and can be ignored by everyone.)
1 Definition: What is cURL
cURL allows data transfer across a wide range of protocols and is a very powerful system. It is widely used for sending data across websites, including things like API interactions and oAuth. cURL is almost omnipotent in its scope of applications, from basic HTTP requests, to more complex FTP uploads or interactive authentication of closed HTTPS websites. Let's take a look at the simple differences between sending a GET and POST request and handling the returned response, as well as some important parameter descriptions.
Before we can do anything with a cURL request, we first need to initialize an instance of cURL. We can achieve this by calling the curl_init() function, which will return a cURL resource. This function receives as one of its parameters the request URL you want to send. In this article, we will not do this step first, and we can implement it in another way in the following process.
2 Notes: Some core settings
Once we get a cURL resource, we can start doing some configuration. Some of the core settings I summarized are listed below.
CURLOPT_RETURNTRANSFER - Returns the response as a string instead of outputting to the screen
CURLOPT_CONNECTTIMEOUT - Connection timeout time
CURLOPT_TIMEOUT - cURL execution timeout
CURLOPT_USERAGENT - Useragent string used for the request
CURLOPT_URL - the URL object to send the request
CURLOPT_POST - Send a request as POST
CURLOPT_POSTFIELDS - Array data in the POST submitted request
3 Create a configuration
We can create a configuration by using the curl_setopt() method, which accepts 3 parameters: cURL resource, setting and setting corresponding value. So we can set the request URL we are sending as shown below.
The code is as follows | Copy code | ||||
curl_setopt($curl, CURLOPT_URL, 'http://www.bKjia.c0m'); |
代码如下 | 复制代码 |
$curl = curl_init('http://www.hzhuti.com'); |
The code is as follows | Copy code | ||||
$curl = curl_init('http://www.hzhuti.com');
|
The code is as follows | Copy code |
$curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => 'http://www.bKjia.c0m' )); |
4 Execution request: curl_exec()
When all options are configured and ready to send a request, we can execute this cURL request by calling curl_exec(). This function will return three different situations:
The code is as follows | Copy code | ||||
|
At this point, $result already contains the response of the page - it may be JSON, a string or the HTML of a complete website. 5 Close request: curl_close()
After you send a request and get the corresponding return result, you need to close the cURL request to release some system resources. By calling the curl_close() method, we can release the resource simply like any other function that requires a resource as a parameter.
6 GET request
GET request is the default request method, and we can use it very straightforwardly. Virtually all of the examples so far have been GET requests. If you want to add some parameters to the request, then you can append these parameters to the URL address as a query string like http://testcURL.com/?item1=value&item2=value2.
Therefore, we can send a GET request to the above URL through the following example and return the corresponding result.
代码如下 | 复制代码 |
// Get cURL resource |
The code is as follows | Copy code | ||||
// Get cURL resource $curl = curl_init(); // Set some options - we are passing in a useragent too here curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => 'http://testcURL.com/?item1=value&item2=value2',CURLOPT_USERAGENT => 'Codular Sample cURL Request' ));
|
The code is as follows | Copy code |
// Get cURL resource $curl = curl_init(); // Set some options - we are passing in a useragent too here curl_setopt_array($curl, array( CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => 'http://www.bKjia.c0m', CURLOPT_USERAGENT => 'Codular Sample cURL Request', CURLOPT_POST => 1, CURLOPT_POSTFIELDS => array( item1 => 'value', item2 => 'value2' ) )); // Send the request & save response to $resp $resp = curl_exec($curl); // Close request to clear up some resources curl_close($curl); |
At this point, you have a POST request: it will produce the same effect as the GET request above, and will return the data to the script so that you can use them as you like.
Example of making https request
The code is as follows
|
Copy code
foreach($vars as $key=>$value)
$fields_string .= $key.'='.$value.'&' ;
$fields_string = substr($fields_string,0,(strlen($fields_string)-1));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); if(!curl_exec($curl)){
curl_setopt($ch, CURLOPT_POST, count($vars) ); |
{
As much as we hate mistakes, you still have to be aware of situations that may arise when using cURL. Because you ultimately have no control over the website you send the request to, and there is no guarantee that the site's response will be the way you expected and that the site will always be in a normal state.The code is as follows | Copy code |
if(!curl_exec($curl)){ Die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl)); } If you want any HTTP response code greater than 400 to generate an error instead of returning the entire HTML page, then you can set CURLOPT_FAILONERROR to true. cURL is a giant, and there are many, many possibilities. Some websites may provide service pages for some user agents. When using the API interface, they may require you to send a special user agent. These are all things we need to pay attention to. If you still want to learn about cURL requests, why not try oAuth with Instagram? http://www.bkjia.com/PHPjc/632735.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632735.htmlTechArticlecURL is a very powerful function in php, which can imitate various user requests, such as imitating user login and sending php Cookie and other operations, let me sort out some related methods for you to read... |

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.
