What is the use of PHP curl_setopt function?

巴扎黑
Release: 2023-03-15 13:12:02
Original
4264 people have browsed it

PHP curl_setopt function is used to set a cURL transfer option, that is, to set an option for a given cURL session handle. The curl_setopt function returns TRUE when successful and FALSE when failed.

What is the use of PHP curl_setopt function?

PHP curl_setopt function

curl_setopt — Sets a cURL transfer option.

Description

bool curl_setopt ( resource $ch , int $option , mixed $value )
Copy after login

Set an option for the given cURL session handle.

Parameters

ch: cURL handle returned by curl_init().

option: CURLOPT_XXX options that need to be set.

value: The value that will be set on the option option.

For the optional parameters of the following options, value should be set to a bool type value:

When ##CURLOPT_COOKIESESSIONCURLOPT_CRLF##CURLOPT_DNS_USE_GLOBAL_CACHECURLOPT_FAILONERRORCURLOPT_FILETIME option of the curl_getinfo() function. curl_getinfo().CURLOPT_FOLLOWLOCATIONPut it in the header and return it to the server recursively. Use ##CURLOPT_FORBID_REUSECURLOPT_FRESH_CONNECTWhen enabled, use the EPRT (or LPRT) command when FTP downloads. When set to When enabled, first before reverting to PASV mode during FTP transfer Try the EPSV command. Disables the EPSV command when set to FALSEWhen enabled append writes to the file instead of overwriting it. ##CURLOPT_FTPASCII## Alias ​​for CURLOPT_TRANSFERTEXT. CURLOPT_HEADERCURLINFO_HEADER_OUTAvailable starting with PHP 5.1.3. CURLINFO_The prefix is ​​intentional. After the connection is established, visit When enabled, the BODY part in HTML will not be output. ##CURLOPT_NOPROGRESSClose the progress bar of curl transmission when enabled, the default for this item Set to enabled. CURLOPT_NOSIGNALCURLOPT_POSTapplication/x-www-form-urlencoded ##CURLOPT_PUTCURLOPT_INFILESIZEReturn the information obtained by curl_exec() in the form of a file stream instead of Direct output. After disabling cURL will terminate verification from the server. Use the option to set the certificate directory. ​ ​ ​ If Use ASCII mode for FTP transfers when enabled. For LDAP, it retrieves plain text information rather than HTML. On Windows systems, the system does not set Multiple headers generated using CURLOPT_FOLLOWLOCATIONAllows file uploads when enabled. ##CURLOPT_VERBOSEWhen enabled, all information will be reported and stored in STDERR or the specified
OptionsOptionalvalueValueRemarks
CURLOPT_AUTOREFERERWhen redirected according to Location:, the Referer: information in the header is automatically set.
##CURLOPT_BINARYTRANSFERCURLOPT_RETURNTRANSFER is enabled, return the native ( Raw) output.
When enabled, curl will only pass one session cookie and ignore other cookies. By default In this case, 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.
When enabled, convert Unix line feeds into carriage returns and line feeds.
When enabled, a global DNS cache will be enabled. This item is thread-safe. , and is enabled by default.
Display HTTP status code, the default behavior is to ignore HTTP information with a number less than or equal to 400 .
When enabled, an attempt will be made to modify information in the remote document. The result information will be returned through the CURLINFO_FILETIME
When enabled, the server will return the " Location: "CURLOPT_MAXREDIRS to limit the number of recursive returns.
Forcibly disconnects after completing the interaction and cannot be reused.
Force to obtain a new connection to replace the one in the cache.
##CURLOPT_FTP_USE_EPRT
FALSE disables EPRT and LPRT, use the PORT command only.##CURLOPT_FTP_USE_EPSV
. CURLOPT_FTPAPPEND

##CURLOPT_FTPLISTONLYWhen enabled, only the name of the FTP directory is listed.
When enabled, the header file information will be output as a data stream.
The request string for the tracking handle when enabled.
CURLOPT_HTTPGETWhen enabled, the HTTP method will be set to GET. Because GET is the default, it is only used when it is modified. .
CURLOPT_HTTPPROXYTUNNELWhen enabled, it will be transmitted through HTTP proxy.
CURLOPT_MUTEWhen enabled, all modified parameters in the cURL function will be restored to their default values.
##CURLOPT_NETRC~/.netrc The file obtains username and password information to connect to the remote site.
CURLOPT_NOBODY

Note

:PHP automatically sets this option to

TRUE

, this option should only be changed for debugging purposes .


When enabled, ignore all curl passed to php signal of. This item is enabled by default during SAPI multi-threaded transmission. cURL was added in 7.10.
When enabled, a regular POST request will be sent, the type is: , just like form submission.
Allows HTTP to send files when enabled. CURLOPT_INFILE## ​​must be set at the same time. # and .
##CURLOPT_RETURNTRANSFER

CURLOPT_SSL_VERIFYPEER
CURLOPT_CAINFO option to set the certificate. Use the CURLOPT_CAPATHCURLOPT_SSL_VERIFYPEER (default value is 2) is enabled, CURLOPT_SSL_VERIFYHOST needs to be set to TRUE otherwise set to FALSE. Defaults to TRUE since cURL 7.10. Starting with cURL 7.10, bundle installation is defaulted. CURLOPT_TRANSFERTEXT
STDOUT to binary mode. ##CURLOPT_UNRESTRICTED_AUTH
Username and password information continues to be appended to locations, even if the domain name has changed. CURLOPT_UPLOAD

CURLOPT_STDERR.

For the optional parameters of the following options, value should be set to an integer type value:

Either CURLCLOSEPOLICY_LEAST_RECENTLY_USED or CURLCLOSEPOLICY_OLDEST, there are three other CURLCLOSEPOLICYs, but cURL does not support them yet. ##CURLOPT_CONNECTTIMEOUTCURLOPT_CONNECTTIMEOUT_MSCURLOPT_DNS_CACHE_TIMEOUT##CURLOPT_FTPSSLAUTH (try SSL first) , ##CURLOPT_HTTP_VERSIONCURL_HTTP_VERSION_1_0Set the size limit of uploaded files in bytes. When the transmission speed is less than CURLOPT_LOW_SPEED_LIMIT##CURLOPT_LOW_SPEED_TIMEWhen the transmission speed is less than CURLOPT_LOW_SPEED_LIMIT(bytes/sec ), PHP will determine whether to cancel the transmission because it is too slow based on CURLOPT_CLOSEPOLICY## will be passed #Determine which connections should be stopped. Specifies the maximum number of HTTP redirects. This option is the same as is used to specify the connection port. (Optional) Bit field pointers to CURLPROTO_*. The available protocol options are: CURLPROTO_HTTP, CURLPROTO_HTTPS, CURLPROTO_FTP, CURLPROTO_FTPS, CURLPROTO_SCP, CURLPROTO_SFTP, CURLPROTO_TELNET, CURLPROTO_LDAP, CURLPROTO_LDAPS, CURLPROTO_DICT, CURLPROTO_FILE, CURLPROTO _TFTP,CURLPROTO_ALL in cURL 7.19. 4 was added. The bit field of refers to the bit field. If enabled, the bitfield value limits which protocols libcurl can use during transfers. This will allow you to compile libcurl with support for many protocols, but be restricted to using only a subset of them that are allowed to be used. By default libcurl will use all protocols it supports. See . The available protocol options are: CURLPROTO_HTTP, CURLPROTO_HTTPS, CURLPROTO_FTP, CURLPROTO_FTPS, CURLPROTO_SCP, CURLPROTO_SFTP, CURLPROTO_TELNET, CURLPROTO_LDAP, CURLPROTO_LDAPS, CURLPROTO_DICT, CURLPROTO_FILE, CURLPROTO _TFTP,CURLPROTO_ALL in cURL 7.19. 4 was added. to set the corresponding options. For proxy authentication only and CURLAUTH_NTLM are currently supported. . was added in cURL 7.19.4. Pass a byte offset when resuming transmission (used for resumed transmission). ##CURLOPT_SSL_VERIFYHOSTCURLOPT_SSLVERSION##CURLOPT_TIMECONDITION If it has been edited, use CURLOPT_TIMEOUT Set the maximum number of milliseconds cURL is allowed to execute. Set a timestamp used by .
OptionsOptionalvalueValueRemarks
CURLOPT_BUFFERSIZEThe size of the cache read into the data obtained each time, but there is no guarantee that this value will be filled every time. was added in cURL 7.10.
##CURLOPT_CLOSEPOLICY
The time to wait before initiating a connection. If set to 0, it will wait indefinitely .
The time to wait for a connection attempt, in milliseconds. If set to 0, wait infinitely. was added in cURL 7.16.2. Available starting with PHP 5.2.3.
Set the time to save DNS information in memory, the default is 120 seconds.
FTP verification method: CURLFTPAUTH_SSLCURLFTPAUTH_TLS (try TLS first) or CURLFTPAUTH_DEFAULT (let cURL decide automatically). was added in cURL 7.12.2.
CURL_HTTP_VERSION_NONE (default value, let cURL decide which version to use), (force HTTP/1.0) or CURL_HTTP_VERSION_1_1 (force HTTP/1.1).
##CURLOPT_INFILESIZE
##CURLOPT_LOW_SPEED_LIMIT
(bytes/sec ), PHP will determine whether to cancel the transmission because it is too slow based on CURLOPT_LOW_SPEED_TIME.
CURLOPT_LOW_SPEED_TIME. ##CURLOPT_MAXCONNECTS
The maximum number of connections allowed, if exceeded,
##CURLOPT_MAXREDIRS CURLOPT_FOLLOWLOCATION
is used together.
CURLOPT_PORT
##CURLOPT_PROTOCOLS . If enabled, the bitfield value limits which protocols libcurl can use during transfers. This will allow you to compile libcurl with support for many protocols, but be restricted to using only a subset of them that are allowed to be used. By default libcurl will use all protocols it supports. See
CURLOPT_REDIR_PROTOCOLS
CURLOPT_PROTOCOLSCURLPROTO_*CURLOPT_REDIR_PROTOCOLS
CURLOPT_PROXYAUTHVerification method for HTTP proxy connection. Use the bitfield flags in CURLOPT_HTTPAUTHCURLAUTH_BASIC
was added in cURL 7.10.7. CURLOPT_PROXYPORTThe port of the proxy server. The port can also be set in CURLOPT_PROXY
CURLOPT_PROXYTYPE is either CURLPROXY_HTTP (default) or CURLPROXY_SOCKS5. was added in cURL 7.10. Bit field value in
CURLOPT_REDIR_PROTOCOLS##CURLPROTO_*. If enabled, the bitfield value will limit the protocols that the transport thread can use when following a redirect when CURLOPT_FOLLOWLOCATION is enabled. This will allow you to restrict the transport thread to a subset of allowed protocols when redirecting. By default libcurl will allow all protocols except FILE and SCP. This is slightly different from the 7.19.4 pre-release version which unconditionally follows all supported protocols. For protocol constants, please refer to CURLOPT_PROTOCOLS.
CURLOPT_RESUME_FROM
1 Check whether a common name exists in the server SSL certificate. Translator's Note: Common Name generally means filling in the domain name (domain) or subdomain (sub domain) for which you are going to apply for an SSL certificate. 2 Check that the common name exists and matches the provided host name.
The SSL version to use (2 or 3). By default PHP will detect this value by itself, although in some cases it may need to be set manually.
If after a certain time specified by CURLOPT_TIMEVALUECURL_TIMECOND_IFMODSINCE to return to the page. If it has not been modified and CURLOPT_HEADER is true, a "304 Not Modified" header will be returned. # If ##CURLOPT_HEADER is false, use CURL_TIMECOND_IFUNMODSINCE. The default value is CURL_TIMECOND_IFUNMODSINCE.
Set the maximum number of seconds cURL is allowed to execute.
##CURLOPT_TIMEOUT_MS
was added in cURL 7.16.2. Available from PHP 5.2.3 onwards. CURLOPT_TIMEVALUE
CURLOPT_TIMECONDITION. By default, CURL_TIMECOND_IFMODSINCE is used

For the optional parameters of the following options, value should be set to a string type value:

Set the ##CURLOPT_COOKIEFILECURLOPT_COOKIEJAR##CURLOPT_CUSTOMREQUEST" GET"Similar to ##CURLOPT_ENCODING"Accept-Encoding: "CURLOPT_FTPPORT##CURLOPT_INTERFACECURLOPT_KRB4LEVEL, ##CURLOPT_POSTFIELDSpara1=val1¶2=val2&...CURLOPT_PROXYA number used to connect to the proxyA file name used to generate SSL random number seeds. ##CURLOPT_RANGEIn the form of "X-Y", where X and Y is the range of optional data obtained, measured in bytes. The HTTP transfer thread also supports several such duplicates separated by commas such as "Referer: " content. RC4-SHA and TLSv1##CURLOPT_SSLCERTPASSWD certificate. ##CURLOPT_SSLKEYTYPECURLOPT_SSLKEY##CURLOPT_URLSet in function. ##CURLOPT_USERAGENT Pass the username and password required for a connection in the format: "[username]:[password]"
OptionsOptional valueValueRemarks
CURLOPT_CAINFO One holds 1 or more The file name of the certificate used for verification by the server. This parameter is only meaningful when used with CURLOPT_SSL_VERIFYPEER. ​ .
CURLOPT_CAPATHA directory that holds multiple CA certificates. This option is used with CURLOPT_SSL_VERIFYPEER.
##CURLOPT_COOKIE"Cookie: " part of the HTTP request Content. Multiple cookies are separated by a semicolon followed by a space (for example, "fruit=apple; colour=red").
The file name containing cookie data. The format of the cookie file can be Netscape format. Or just save the pure HTTP header information to the file.
A file that saves cookie information after the connection is completed.
Use a custom request message instead or

"HEAD" as an HTTP request. This is useful for performing "DELETE" or other more covert HTTP requests. Valid values ​​include "GET", "POST", "CONNECT", etc. That is, don't enter the entire HTTP request here. For example, entering "GET /index.html HTTP/1.0\r\n\r\n" is incorrect.

Note
:

Do not use this custom request method until you are sure that the server supports it.


##CURLOPT_EGDSOCKETCURLOPT_RANDOM_FILE, except for an Entropy Gathering Daemon socket.
in the HTTP request header value. Supported encodings are "identity", "deflate" and "gzip". If it is the empty string "", the request header will send all supported encoding types. was added in cURL 7.10.
This value will be used to obtain the IP address required for the FTP "POST" command. The "POST" command tells the remote server to connect to the IP address we specified. This string can be a plain text IP address, a hostname, a network interface name (under UNIX) or just a '-' to use the default IP address.
The network sending interface name can be an interface name, IP address or a CPU name.
KRB4 (Kerberos 4) security level. Any of the following values ​​are valid (in order from lowest to highest): "clear""safe", "confidential", "private".. If the string matches none of these, "private" will be used. Setting this option to NULL will disable KRB4 security authentication. Currently KRB4 security authentication can only be used for FTP transmission.
All data is sent using the "POST" operation in the HTTP protocol. To send a file, prefix the file name with @ and use the full path. This parameter can be passed through a urlencoded string like '' or an array with the field name as the key and the field data as the value. If value is an array, the Content-Type header will be set to multipart/form-data.
HTTP proxy channel.
##CURLOPT_PROXYUSERPWD
"[username]:[ password]" format string. ##CURLOPT_RANDOM_FILE

"X-Y,N-M". ##CURLOPT_REFERER
In the HTTP request header
CURLOPT_SSL_CIPHER_LIST
A list of SSL encryption algorithms. For example,
are both available encryption lists. CURLOPT_SSLCERT
The name of a file containing a certificate in PEM format.
The password required to use the
CURLOPT_SSLCERT
CURLOPT_SSLCERTTYPEType of certificate. Supported formats are "PEM" (default), "DER" and "ENG". was added in cURL 7.9.3.
CURLOPT_SSLENGINEEncryption engine variable used for the SSL private key specified in CURLOPT_SSLKEY.
CURLOPT_SSLENGINE_DEFAULTVariables used for asymmetric encryption operations.
CURLOPT_SSLKEYThe name of the file containing the SSL private key.
##CURLOPT_SSLKEYPASSWDThe SSL specified in

CURLOPT_SSLKEY The password for the private key.

Note:

Since this option contains sensitive password information, remember to keep this PHP script safe.


The encryption type of the private key. The supported key types are "PEM" (default value), "DER" and "ENG".
The URL address that needs to be obtained can also be obtained in curl_init()
Include a "User-Agent: "# in the HTTP request ##Header string. ##CURLOPT_USERPWD
. For the optional parameters of the following options, value should be set to an array:
Options

OptionalvalueValueCURLOPT_HTTP200ALIASES200 response code array, the response in the array is considered a correct response, otherwise it is considered an error. CURLOPT_HTTPHEADERAn array used to set HTTP header fields. Use an array of the following form to set:                         array('Content-type: text/plain', 'Content-length: 100')#CURLOPT_POSTQUOTEA set of FTP commands executed on the server after the FTP request is executed.

对于下面的这些option的可选参数,value应该被设置一个流资源 (例如使用fopen()):

Remarks
was added in cURL 7.10.3.

##CURLOPT_QUOTE
#A set of FTP commands to be executed on the server before the FTP request.
选项可选value
CURLOPT_FILE设置输出文件的位置,值是一个资源类型,默认为STDOUT (浏览器)。
CURLOPT_INFILE在上传文件的时候需要读取的文件地址,值是一个资源类型。
CURLOPT_STDERR设置一个错误输出地址,值是一个资源类型,取代默认的STDERR
CURLOPT_WRITEHEADER设置header部分内容的写入的文件地址,值是一个资源类型。

对于下面的这些option的可选参数,value应该被设置为一个回调函数名:

选项可选value
CURLOPT_HEADERFUNCTION设置一个回调函数,这个函数有两个参数,第一个是cURL的资源句柄,第二个是输出的header数据。header数据的输出必须依赖这个函数,返回已写入的数据大小。
CURLOPT_PASSWDFUNCTION设置一个回调函数,有三个参数,第一个是cURL的资源句柄,第二个是一个密码提示符,第三个参数是密码长度允许的最大值。返回密码的值。
CURLOPT_PROGRESSFUNCTION设置一个回调函数,有三个参数,第一个是cURL的资源句柄,第二个是一个文件描述符资源,第三个是长度。返回包含的数据。
CURLOPT_READFUNCTION回调函数名。该函数应接受三个参数。第一个是 cURL resource;第二个是通过选项 CURLOPT_INFILE 传给 cURL 的 stream resource;第三个参数是最大可以读取的数据的数量。回 调函数必须返回一个字符串,长度小于或等于请求的数据量(第三个参数)。一般从传入的 stream resource 读取。返回空字符串作为 EOF(文件结束) 信号。
CURLOPT_WRITEFUNCTION回调函数名。该函数应接受两个参数。第一个是 cURL resource;第二个是要写入的数据字符串。数 据必须在函数中被保存。函数必须返回准确的传入的要写入数据的字节数,否则传输会被一个错误所中 断。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE。

实例

初始化一个新的cURL会话并获取一个网页

<?php
// 创建一个新cURL资源
$ch = curl_init();
// 设置URL和相应的选项
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);
// 抓取URL并把它传递给浏览器
curl_exec($ch);
//关闭cURL资源,并且释放系统资源
curl_close($ch);
?>
Copy after login

上传文件实例:

<?php
/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/
$ch = curl_init();
$data = array(&#39;name&#39; => &#39;Foo&#39;, &#39;file&#39; => &#39;@/home/user/test.png&#39;);
curl_setopt($ch, CURLOPT_URL, &#39;http://localhost/upload.php&#39;);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
?>
Copy after login

以上实例输出结果如下:

Array
(
    [name] => Foo
)
Array
(
    [file] => Array
        (
            [name] => test.png
            [type] => image/png
            [tmp_name] => /tmp/phpcpjNeQ
            [error] => 0
            [size] => 279
        )
)
Copy after login

更多相关知识,请访问 PHP中文网!!

The above is the detailed content of What is the use of PHP curl_setopt function?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template