PHP curl_setopt function

PHP Calendar 参考手册PHP cURL Reference Manual

(PHP 4 >= 4.0.2, PHP 5)

curl_setopt — Set a cURL transfer option.


Description

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

Sets an option for the given cURL session handle.


Parameters

ch

cURL handle returned by curl_init().

option

The CURLOPT_XXX option to set.

value

The value to set on the option.

For the following optional parameters for these options, value should be set to a bool value:

Option ValuevalueValue Notes
CURLOPT_AUTOREFERER When followingLocation:redirects, automatically set the headerReferer:information.
CURLOPT_BINARYTRANSFER When enabledCURLOPT_RETURNTRANSFER, return native (Raw) output.
CURLOPT_COOKIESESSION When enabled, cURL will only pass a session cookie and ignore other cookies. By default, cURL returns all cookies to the server. Session cookies are those that exist to determine whether the server-side session is valid.
CURLOPT_CRLF When enabled, convert Unix newlines to carriage return and line feed.
CURLOPT_DNS_USE_GLOBAL_CACHE When enabled, a global DNS cache is enabled. This option is thread-safe and enabled by default.
CURLOPT_FAILONERROR Display HTTP status codes. The default behavior is to ignore HTTP messages with codes less than or equal to 400.
CURLOPT_FILETIME When enabled, it will attempt to modify information in the remote document. The result information will be via the curl_getinfo() function'sCURLINFO_FILETIMEoption returned. curl_getinfo().
CURLOPT_FOLLOWLOCATION When enabled, will take the server-returned"Location: "put it in the header and recursively return it to the server, usingCURLOPT_MAXREDIRScan limit the number of recursive returns.
CURLOPT_FORBID_REUSE Force disconnection after interaction is complete; cannot be reused.
CURLOPT_FRESH_CONNECT Force a new connection to be obtained, replacing the cached connection.
CURLOPT_FTP_USE_EPRT When enabled, during FTP download, use the EPRT (or LPRT) command. Set toFALSEdisables EPRT and LPRT, and uses the PORT command only.
CURLOPT_FTP_USE_EPSV When enabled, during FTP transfer, it first attempts the EPSV command before reverting to PASV mode. Set toFALSEdisables the EPSV command.
CURLOPT_FTPAPPEND When enabled, append to file instead of overwriting it.
CURLOPT_FTPASCII CURLOPT_TRANSFERTEXTalias of.
CURLOPT_FTPLISTONLY When enabled, list only FTP directory names.
CURLOPT_HEADER When enabled, header file information is output as a data stream.
CURLINFO_HEADER_OUT When enabled, trace the request string of the handle. Available from PHP 5.1.3 onwards.CURLINFO_The prefix is intentional.
CURLOPT_HTTPGET When enabled, the HTTP method is set to GET. Since GET is the default, it is only used when modified.
CURLOPT_HTTPPROXYTUNNEL When enabled, transfer through an HTTP proxy.
CURLOPT_MUTE When enabled, restores all modified parameters in the cURL function to their default values.
CURLOPT_NETRC After the connection is established, access~/.netrcfile to obtain username and password information to connect to the remote site.
CURLOPT_NOBODY When enabled, the BODY part of HTML will not be output.
CURLOPT_NOPROGRESS

When enabled, the progress bar for curl transfer is disabled. This option is enabled by default.

Note:

PHP automatically sets this option toTRUE, this option should only be changed for debugging purposes.

CURLOPT_NOSIGNAL When enabled, all signals passed by curl to PHP are ignored. This option is enabled by default during SAPI multi-threaded transfer. Added in cURL 7.10.
CURLOPT_POST When enabled, a regular POST request is sent, with type:application/x-www-form-urlencoded, just like a form submission.
CURLOPT_PUT When enabled, HTTP file sending is allowed; must also setCURLOPT_INFILEandCURLOPT_INFILESIZE。
CURLOPT_RETURNTRANSFER Return the information obtained by curl_exec() as a file stream, instead of outputting it directly.
CURLOPT_SSL_VERIFYPEER When disabled, cURL will stop verifying from the server. UseCURLOPT_CAINFOoption to set certificate useCURLOPT_CAPATHoption to set certificate directoryCURLOPT_SSL_VERIFYPEER(default value 2) is enabled,CURLOPT_SSL_VERIFYHOSTneeds to be set toTRUEotherwise set toFALSE。 Defaults to since cURL 7.10TRUE. Binded by default since cURL 7.10.
CURLOPT_TRANSFERTEXT When enabled, ASCII mode is used for FTP transfer. For LDAP, it retrieves plain text information instead of HTML. On Windows systems, the system will not setSTDOUTto binary mode.
CURLOPT_UNRESTRICTED_AUTH When usingCURLOPT_FOLLOWLOCATIONcontinue to append username and password information among multiple locations in the generated header, even if the domain has changed.
CURLOPT_UPLOAD When enabled, file upload is allowed.
CURLOPT_VERBOSE When enabled, reports all information, stored inSTDERRor the specifiedCURLOPT_STDERRin.

For the following optional parameters for these options, value should be set to an integer value:

Option ValuevalueValue Notes
CURLOPT_BUFFERSIZE The size of the cache read from each fetched data, but there is no guarantee that this value will be filled each time. Added in cURL 7.10.
CURLOPT_CLOSEPOLICY Either CURLCLOSEPOLICY_LEAST_RECENTLY_USED or CURLCLOSEPOLICY_OLDEST. There are three other CURLCLOSEPOLICY values, but cURL does not support them yet.
CURLOPT_CONNECTTIMEOUT The time to wait before initiating a connection; if set to 0, waits indefinitely.
CURLOPT_CONNECTTIMEOUT_MS The time to wait when attempting to connect, in milliseconds. If set to 0, waits indefinitely. Added in cURL 7.16.2. Available from PHP 5.2.3.
CURLOPT_DNS_CACHE_TIMEOUT Set the time to store DNS information in memory, default is 120 seconds.
CURLOPT_FTPSSLAUTH FTP authentication method:CURLFTPAUTH_SSL(try SSL first),CURLFTPAUTH_TLS(try TLS first) orCURLFTPAUTH_DEFAULT(let cURL decide automatically). Added in cURL 7.12.2.
CURLOPT_HTTP_VERSION CURL_HTTP_VERSION_NONE(default, let cURL determine which version to use),CURL_HTTP_VERSION_1_0(force HTTP/1.0) orCURL_HTTP_VERSION_1_1(force HTTP/1.1).
CURLOPT_INFILESIZE Set the size limit of uploaded files, in bytes.
CURLOPT_LOW_SPEED_LIMIT When the transfer speed is less thanCURLOPT_LOW_SPEED_LIMIT(bytes/sec), PHP will based onCURLOPT_LOW_SPEED_TIMEto determine whether to cancel the transfer because it is too slow.
CURLOPT_LOW_SPEED_TIME When the transfer speed is less thanCURLOPT_LOW_SPEED_LIMIT(bytes/sec), PHP will based onCURLOPT_LOW_SPEED_TIMEto determine whether to cancel the transfer because it is too slow.
CURLOPT_MAXCONNECTS The maximum number of allowed connections; when exceeded, it will useCURLOPT_CLOSEPOLICYto decide which connections should be stopped.
CURLOPT_MAXREDIRS Specify the maximum number of HTTP redirects. This option is used withCURLOPT_FOLLOWLOCATIONtogether.
CURLOPT_PORT Used to specify the connection port. (Optional)
CURLOPT_PROTOCOLS CURLPROTO_*bitmask. If enabled, the bitmask value will limit which protocols libcurl can use during transfer. This allows you to support many protocols when compiling libcurl, but restrict it to only a subset of allowed protocols. By default, libcurl will use all the protocols it supports. SeeCURLOPT_REDIR_PROTOCOLS. 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 Added in cURL 7.19.4.
CURLOPT_PROTOCOLS CURLPROTO_*bitmask. If enabled, the bitmask value will limit which protocols libcurl can use during transfer. This allows you to support many protocols when compiling libcurl, but restrict it to only a subset of allowed protocols. By default, libcurl will use all the protocols it supports. SeeCURLOPT_REDIR_PROTOCOLSAvailable 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 Added in cURL 7.19.4.
CURLOPT_PROXYAUTH HTTP proxy connection authentication method. Use theCURLOPT_HTTPAUTHbit-field flags to set the corresponding option. For proxy authentication, onlyCURLAUTH_BASICandCURLAUTH_NTLMis currently supported. Added in cURL 7.10.7.
CURLOPT_PROXYPORT Proxy server port. The port can also beCURLOPT_PROXYset in
CURLOPT_PROXYTYPE is notCURLPROXY_HTTP(default value) orCURLPROXY_SOCKS5。 Added in cURL 7.10.
CURLOPT_REDIR_PROTOCOLS CURLPROTO_*The bit-field value. If enabled, the bit-field value will restrict the transfer thread toCURLOPT_FOLLOWLOCATIONthe protocols that can be used when following a redirect. This will allow you to restrict the transfer thread to a subset of allowed protocols during redirects. By default, libcurl will allow all protocols except FILE and SCP. This is somewhat different from the 7.19.4 pre-release version, which unconditionally followed all supported protocols. For protocol constants, please refer toCURLOPT_PROTOCOLS。 Added in cURL 7.19.4.
CURLOPT_RESUME_FROM Pass a byte offset when resuming the transfer (used for resuming interrupted transfers).
CURLOPT_SSL_VERIFYHOST 1 Check whether a common name exists in the server SSL certificate. Translator's note: Common Name generally refers to the domain or subdomain for which you are about to apply for an SSL certificate. 2 Check whether the common name exists and matches the provided hostname.
CURLOPT_SSLVERSION The SSL version to use (2 or 3). By default, PHP will detect this value itself, although in some cases it needs to be set manually.
CURLOPT_TIMECONDITION IfCURLOPT_TIMEVALUEhas been edited after the specified time, then useCURL_TIMECOND_IFMODSINCEreturn the page; if it has not been modified, andCURLOPT_HEADERis true, return a"304 Not Modified"header,CURLOPT_HEADERis false, useCURL_TIMECOND_IFUNMODSINCE, the default isCURL_TIMECOND_IFUNMODSINCE。
CURLOPT_TIMEOUT Set the maximum number of seconds cURL is allowed to execute.
CURLOPT_TIMEOUT_MS Set the maximum number of milliseconds cURL is allowed to execute. Added in cURL 7.16.2. Available from PHP 5.2.3.
CURLOPT_TIMEVALUE Set aCURLOPT_TIMECONDITIONtimestamp to use; by default, it usesCURL_TIMECOND_IFMODSINCE。

For the following options, the value parameter should be set to a string value:

Option OptionalvalueValue Remarks
CURLOPT_CAINFO A filename containing one or more certificates for server verification. This parameter is only meaningful when used withCURLOPT_SSL_VERIFYPEERIt is only meaningful when used together.
CURLOPT_CAPATH A directory containing multiple CA certificates. This option is used withCURLOPT_SSL_VERIFYPEERIt is used together.
CURLOPT_COOKIE Set the"Cookie: "part of the HTTP request. Multiple cookies are separated by semicolons, with a space after the semicolon (e.g., "fruit=apple; colour=red")。
CURLOPT_COOKIEFILE The filename containing cookie data. The cookie file format can be Netscape format, or just plain HTTP header information stored in a file.
CURLOPT_COOKIEJAR The file to save cookie information to after the connection ends.
CURLOPT_CUSTOMREQUEST

Use a custom request message instead of"GET"or"HEAD"as the HTTP request. This is useful for performing"DELETE"or other more obscure HTTP requests. Valid values include"GET","POST","CONNECT"etc. That is, do not 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 before confirming that the server supports this custom request method.

CURLOPT_EGDSOCKET Similar toCURLOPT_RANDOM_FILE, except an Entropy Gathering Daemon socket.
CURLOPT_ENCODING In the HTTP request header"Accept-Encoding: "value. Supported encodings are"identity","deflate"and"gzip". If an empty string"", the request header will send all supported encoding types. Added in cURL 7.10.
CURLOPT_FTPPORT 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 specify. This string can be a plain-text IP address, a hostname, a network interface name (on UNIX), or simply a '-' to use the default IP address.
CURLOPT_INTERFACE Network sending interface name; it can be an interface name, IP address, or hostname.
CURLOPT_KRB4LEVEL KRB4 (Kerberos 4) security level. Any of the following values are valid (in order from low to high):"clear"、"safe"、"confidential"、"private".. If the string does not match any of these, it will use"private". This option set toNULLwill disable KRB4 security authentication. Currently, KRB4 security authentication can only be used for FTP transfers.
CURLOPT_POSTFIELDS All data is sent using the "POST" operation in the HTTP protocol. To send a file, prefix the filename with@prefix and use the full path. This parameter can be a urlencoded string similar to 'para1=val1&para2=val2&...' or an array with field names as keys and field data as values. Ifvalueis an array,Content-Typeheader will be set tomultipart/form-data。
CURLOPT_PROXY HTTP proxy tunnel.
CURLOPT_PROXYUSERPWD A"[username]:[password]"format string used to connect to the proxy.
CURLOPT_RANDOM_FILE A filename used to generate the SSL random number seed.
CURLOPT_RANGE with"X-Y"in the form, where X and Y are optional and specify the range of data to fetch, in bytes. The HTTP transfer thread also supports several such repeated items separated by commas, such as"X-Y,N-M"。
CURLOPT_REFERER In the HTTP request header"Referer: "content.
CURLOPT_SSL_CIPHER_LIST A list of SSL encryption algorithms. For example,RC4-SHAandTLSv1are all available encryption lists.
CURLOPT_SSLCERT A filename containing a certificate in PEM format.
CURLOPT_SSLCERTPASSWD UseCURLOPT_SSLCERTthe password required by the certificate.
CURLOPT_SSLCERTTYPE Certificate type. Supported formats are"PEM"(default),"DER"and"ENG"。 Added in cURL 7.9.3.
CURLOPT_SSLENGINE Used inCURLOPT_SSLKEYthe encryption engine variable for the SSL private key specified in
CURLOPT_SSLENGINE_DEFAULT The variable used for asymmetric encryption operations.
CURLOPT_SSLKEY The filename containing the SSL private key.
CURLOPT_SSLKEYPASSWD

InCURLOPT_SSLKEYThe password for the SSL private key specified in

Note:

Because this option contains sensitive password information, remember to ensure the security of this PHP script.

CURLOPT_SSLKEYTYPE CURLOPT_SSLKEYThe encryption type of the private key specified in ... Supported key types are"PEM"(default),"DER"and"ENG"。
CURLOPT_URL The URL to fetch, which can also be set incurl_init()the function.
CURLOPT_USERAGENT Include a"User-Agent: "header string in the HTTP request.
CURLOPT_USERPWD Pass the username and password required for the connection, in the format:"[username]:[password]"。

For the following options, the value parameter should be set to an array:

Option OptionalvalueValue Remarks
CURLOPT_HTTP200ALIASES An array of 200 response codes. The response codes in the array are considered correct responses, otherwise they are considered errors. Added in cURL 7.10.3.
CURLOPT_HTTPHEADER An array used to set HTTP header fields. Use an array in the following form: array('Content-type: text/plain', 'Content-length: 100')
CURLOPT_POSTQUOTE A set of FTP commands to execute on the server after the FTP request is executed.
CURLOPT_QUOTE A set of FTP commands to execute on the server before the FTP request.

For the following options, the value parameter should be set to a stream resource (e.g., using fopen()):

Option OptionalvalueValue
CURLOPT_FILE Set the location of the output file; the value is a resource type, defaulting toSTDOUT(browser).
CURLOPT_INFILE The file location to read from when uploading a file; the value is a resource type.
CURLOPT_STDERR Set an error output location; the value is a resource type, replacing the defaultSTDERR。
CURLOPT_WRITEHEADER Set the file location for writing the header section content; the value is a resource type.

For the following options, the value parameter should be set to a callback function name:

Option OptionalvalueValue
CURLOPT_HEADERFUNCTION Set a callback function with two parameters: the first is the cURL resource handle, and the second is the output header data. The output of header data must rely on this function. Return the size of the data written.
CURLOPT_PASSWDFUNCTION Set a callback function with three parameters: the first is the cURL resource handle, the second is a password prompt, and the third is the maximum allowed password length. Return the password value.
CURLOPT_PROGRESSFUNCTION Set a callback function with three parameters: the first is the cURL resource handle, the second is a file descriptor resource, and the third is the length. Return the contained data.
CURLOPT_READFUNCTION Callback function name. This function should accept three parameters. The first is a cURL resource; the second is the stream resource passed via the optionCURLOPT_INFILEto cURL; the third parameter is the maximum amount of data that can be read. The callback function must return a string with a length less than or equal to the requested data amount (the third parameter). Generally read from the passed-in stream resource. Returning an empty string asEOF(end-of-file) signal.
CURLOPT_WRITEFUNCTION Callback function name. This function should accept two parameters. The first is a cURL resource; the second is the data string to be written. The data must be saved in the function. The function must return the exact number of bytes of the data passed in to be written, otherwise the transfer will be interrupted by an error.

Return Values

Returns TRUE on success, or FALSE on failure.


Changelog

Version Description
5.2.10 IntroducedCURLOPT_PROTOCOLS, and CURLOPT_REDIR_PROTOCOLS.
5.1.0 IntroducedCURLOPT_AUTOREFERER, CURLOPT_BINARYTRANSFER, CURLOPT_FTPSSLAUTH, CURLOPT_PROXYAUTH, and CURLOPT_TIMECONDITION.
5.0.0 IntroducedCURLOPT_FTP_USE_EPRT, CURLOPT_NOSIGNAL, CURLOPT_UNRESTRICTED_AUTH, CURLOPT_BUFFERSIZE, CURLOPT_HTTPAUTH, CURLOPT_PROXYPORT, CURLOPT_PROXYTYPE, CURLOPT_SSLCERTTYPE, and CURLOPT_HTTP200ALIASES.

Examples

Initialize a new cURL session and fetch a web page

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

File upload example:

<?php

/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/

$ch = curl_init();

$data = array('name' => 'Foo', 'file' => '@/home/user/test.png');

curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
?>

The above example will output:

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

)


Notes

Passing an array to CURLOPT_POSTFIELDS will cause cURL to encode the data as multipart/form-data, while passing a URL-encoded string will cause the data to be encoded as application/x-www-form-urlencoded.


PHP Calendar 参考手册PHP cURL Reference

Other Extensions