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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

See all articles