Home Backend Development PHP Tutorial Detailed explanation and usage of php curl parameters

Detailed explanation and usage of php curl parameters

Jul 25, 2016 am 08:55 AM

  1. $cookie_jar = tempnam('./tmp','cookie');
  2. // login
  3. $c=curl_init('http://login_url?username=...
  4. curl_setopt ($c, CURLOPT_RETURNTRANSFER, 1);
  5. curl_setopt($c, CURLOPT_COOKIEJAR, $cookie_jar);
  6. curl_exec($c);
  7. curl_close($c);
  8. $c="url";
  9. $c=curl_init($ c);
  10. curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
  11. curl_setopt($c, CURLOPT_COOKIEFILE, $cookie_jar);
  12. curl_exec($c);
  13. curl_close($c);
  14. ?>
Copy code

2. Post usage Note: The post data must be urlencoded.

  1. $postdata="user=".urlencode($data);
  2. $c=curl_init($c);
  3. curl_setopt($c, CURLOPT_POST, 1);
  4. curl_setopt($ c, CURLOPT_POSTFIELDS, $postdata);
  5. curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
  6. curl_exec($c);
  7. curl_close($c);
  8. ?>
Copy code

CURL detailed explanation curl_close — close a curl session curl_copy_handle — Copy all contents and parameters of a curl connection resource curl_errno — Returns a numeric number containing error information for the current session curl_error — Returns a string containing error information for the current session curl_exec — execute a curl session curl_getinfo — Get information about a curl connection resource handle curl_init — Initialize a curl session

curl_multi_add_handle — Add individual curl handle resources to a curl batch session curl_multi_close — Close a batch handle resource curl_multi_exec — parse a curl batch handle curl_multi_getcontent — Returns a text stream of fetched output curl_multi_info_read — Get the relevant transmission information of the currently parsed curl curl_multi_init — Initialize a curl batch handle resource curl_multi_remove_handle — Remove a handle resource in the curl batch handle resource curl_multi_select — Get all the sockets associated with the cURL extension, which can then be "selected" curl_setopt_array — Set session parameters for a curl as an array curl_setopt — Set session parameters for a curl curl_version — Get curl-related version information The function of the curl_init() function initializes a curl session. The only parameter of the curl_init() function is optional and represents a URL address. The curl_exec() function is used to execute a curl session, and the only parameter is the handle returned by the curl_init() function. The curl_close() function is used to close a curl session. The only parameter is the handle returned by the curl_init() function.

Example:

  1. $ch = curl_init("http://bbs.it-home.org/");
  2. curl_exec($ch);
  3. curl_close($ch);
  4. ?>
Copy code

What the curl_version() function does: Get curl-related version information. The curl_version() function has a parameter. You can test it.

Example:

  1. print_r(curl_version())
  2. ?>
Copy code

The function of curl_getinfo() function is to obtain the information of a curl connection resource handle. The curl_getinfo() function has Two parameters, the first parameter is the resource handle of curl, and the second parameter is the following constants:

  1. $ch = curl_init("http://bbs.it-home.org/");
  2. print_r(curl_getinfo($ch));
  3. ?>
Copy Code

Optional constants include: CURLINFO_EFFECTIVE_URL The last valid url address

CURLINFO_HTTP_CODE Last received HTTP code

CURLINFO_FILETIME The time to obtain the document remotely. If it cannot be obtained, the return value is "-1"

CURLINFO_TOTAL_TIME Time spent on the last transfer

CURLINFO_NAMELOOKUP_TIME Time spent on name resolution

CURLINFO_CONNECT_TIME Time taken to establish connection

CURLINFO_PRETRANSFER_TIME Time taken from establishing connection to preparing for transfer

CURLINFO_STARTTRANSFER_TIME Time elapsed from establishment of connection to start of transfer

CURLINFO_REDIRECT_TIME Time spent redirecting before transaction transfer begins

CURLINFO_SIZE_UPLOAD Total value of uploaded data

CURLINFO_SIZE_DOWNLOAD Total value of downloaded data

CURLINFO_SPEED_DOWNLOAD Average download speed

CURLINFO_SPEED_UPLOAD Average upload speed

CURLINFO_HEADER_SIZE The size of the header part

CURLINFO_HEADER_OUT Send the requested string

CURLINFO_REQUEST_SIZE The size of the request in question in the HTTP request

CURLINFO_SSL_VERIFYRESULT Result of SSL certification verification requested by setting CURLOPT_SSL_VERIFYPEER

CURLINFO_CONTENT_LENGTH_DOWNLOAD Download content length read from Content-Length: field

CURLINFO_CONTENT_LENGTH_UPLOAD Instructions for uploading content size

CURLINFO_CONTENT_TYPE The "Content-type" value of the downloaded content, NULL means that the server did not send a valid "Content-Type: header"

The curl_setopt() function is used to set session parameters for a curl. The curl_setopt_array() function is used to set session parameters for a curl in the form of an array.

Example:

  1. $ch = curl_init();
  2. $fp = fopen("example_homepage.txt", "w");
  3. curl_setopt($ch, CURLOPT_FILE, $fp);
  4. $options = array(
  5. CURLOPT_URL => 'http://bbs.it-home.org/',
  6. CURLOPT_HEADER => false
  7. );
  8. curl_setopt_array($ch, $options);
  9. curl_exec($ch);
  10. curl_close($ch);
  11. fclose($fp);
  12. ?>
Copy code

The parameters that can be set are: CURLOPT_AUTOREFERER Automatically set the referer information in the header

CURLOPT_BINARYTRANSFER When CURLOPT_RETURNTRANSFER is enabled, data will be retrieved and returned

CURLOPT_COOKIESESSION When enabled, curl will only pass one session cookie and ignore other cookies. By default, curl will return all cookies to the server. Session cookies refer to cookies that are used to determine whether the server-side session is valid.

CURLOPT_CRLF When enabled, converts Unix newline characters to carriage return and line feed characters.

CURLOPT_DNS_USE_GLOBAL_CACHE

When enabled, a global DNS cache will be enabled. This item is thread-safe and defaults to true.

CURLOPT_FAILONERROR

Display HTTP status code, the default behavior is to ignore HTTP information with a number less than or equal to 400

CURLOPT_FILETIME

When enabled, an attempt will be made to modify information in the remote document. The result information will be returned through the CURLINFO_FILETIME option of the curl_getinfo() function.

CURLOPT_FOLLOWLOCATION

When enabled, the "Location:" returned by the server will be placed in the header and returned to the server recursively. Use CURLOPT_MAXREDIRS to limit the number of recursive returns.

CURLOPT_FORBID_REUSE

Forcibly disconnect after completing the interaction and cannot be reused.

CURLOPT_FRESH_CONNECT

Force to obtain a new connection to replace the one in the cache.

CURLOPT_FTP_USE_EPRT

TRUE to use EPRT (and LPRT) when doing active FTP downloads. Use FALSE to disable EPRT and LPRT and use PORT only.

Added in PHP 5.0.0.

CURLOPT_FTP_USE_EPSV

TRUE to first try an EPSV command for FTP transfers before reverting back to PASV. Set to FALSE to disable EPSV.

CURLOPT_FTPAPPEND

TRUE to append to the remote file instead of overwriting it.

CURLOPT_FTPASCII

An alias of CURLOPT_TRANSFERTEXT. Use that instead.

CURLOPT_FTPLISTONLY

TRUE to only list the names of an FTP directory.

CURLOPT_HEADER

When enabled, the header file information will be output as a data stream.

CURLOPT_HTTPGET

When enabled, the HTTP method will be set to GET. Because GET is the default, it is only used when it is modified.

CURLOPT_HTTPPROXYTUNNEL

When enabled, it will be transmitted through HTTP proxy.

CURLOPT_MUTE

Restore all modified parameters in the curl function to their default values.

CURLOPT_NETRC

After the connection is established, access the ~/.netrc file to obtain the username and password information to connect to the remote site.

CURLOPT_NOBODY

When enabled, the body part in HTML will not be output.

CURLOPT_NOPROGRESS

Close the progress bar of curl transfer when enabled. The default setting of this item is true

CURLOPT_NOSIGNAL

When enabled, ignore all signals passed by curl to php. This item is turned on by default during SAPI multi-thread transmission. CURLOPT_POST

When enabled, a regular POST request of type: application/x-www-form-urlencoded will be sent, just like a form submission. CURLOPT_PUT

Allow HTTP to send files when enabled, CURLOPT_INFILE and CURLOPT_INFILESIZE must be set at the same time CURLOPT_RETURNTRANSFER

The information obtained by curl_exec() is returned in the form of a file stream instead of being output directly. CURLOPT_SSL_VERIFYPEER

FALSE to stop cURL from verifying the peer's certificate. Alternate certificates to verify against can be specified with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option. CURLOPT_SSL_VERIFYHOST may also need to be TRUE or FALSE if CURLOPT_SSL_VERIFYPEER is disabled (it defaults to 2). TRUE by default as of cURL 7.10. Default bundle installed as of cURL 7.10.

CURLOPT_TRANSFERTEXT

TRUE to use ASCII mode for FTP transfers. For LDAP, it retrieves data in plain text instead of HTML. On Windows systems, it will not set STDOUT to binary mode.

CURLOPT_UNRESTRICTED_AUTH

Continuously append username and password information to multiple locations in the header generated using CURLOPT_FOLLOWLOCATION, even if the domain name has changed.

CURLOPT_UPLOAD

Allow file transfer when enabled

CURLOPT_VERBOSE

When enabled, all information will be reported and stored in STDERR or the specified CURLOPT_STDERR

CURLOPT_BUFFERSIZE

The size of the cache is read each time the data is obtained. This value will be filled every time.

CURLOPT_CLOSEPOLICY

It’s either CURLCLOSEPOLICY_LEAST_RECENTLY_USED or CURLCLOSEPOLICY_OLDEST. There are three others, but curl doesn’t support them yet. .

CURLOPT_CONNECTTIMEOUT

The time to wait before initiating a connection. If set to 0, there will be no waiting.

CURLOPT_DNS_CACHE_TIMEOUT

Set the time to save DNS information in memory, the default is 120 seconds.

CURLOPT_FTPSSLAUTH

The FTP authentication method (when is activated): CURLFTPAUTH_SSL (try SSL first), CURLFTPAUTH_TLS (try TLS first), or CURLFTPAUTH_DEFAULT (let cURL decide).

CURLOPT_HTTP_VERSION

Set the HTTP protocol used by curl, CURL_HTTP_VERSION_NONE (let curl decide by itself), CURL_HTTP_VERSION_1_0 (HTTP/1.0), CURL_HTTP_VERSION_1_1 (HTTP/1.1)

CURLOPT_HTTPAUTH 1 2 Next Page Last Page



Statement of this Website
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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles