PHP curl_setopt Function
(PHP 4 >= 4.0.2, PHP 5)
curl_setopt — Set an option for a cURL transfer.
Description
bool curl_setopt ( resource $ch , int $option , mixed $value )
Sets an option for the given cURL session handle.
Parameters
ch
The cURL handle returned by curl_init().
option
The CURLOPT_XXX option to set.
value
The value to be set on the option.
For the following options, the value should be set to a boolean:
Option | Possible value | Notes |
---|---|---|
CURLOPT_AUTOREFERER | Automatically set the Referer: field in headers when redirecting. | |
CURLOPT_BINARYTRANSFER | Return raw output when CURLOPT_RETURNTRANSFER is enabled. | |
CURLOPT_COOKIESESSION | Enable to only pass a session cookie, ignoring other cookies. By default, cURL passes all cookies to the server. Session cookies are those used to determine if the server-side session is valid. | |
CURLOPT_CRLF | Convert Unix newlines to CRLF newlines. | |
CURLOPT_DNS_USE_GLOBAL_CACHE | Enable a global DNS cache. This is thread-safe and is enabled by default. | |
CURLOPT_FAILONERROR | Display HTTP status code; by default, HTTP messages with codes less than or equal to 400 are ignored. | |
CURLOPT_FILETIME | Attempt to retrieve the modification date of the remote document. The result can be obtained using the CURLINFO_FILETIME option with curl_getinfo(). | |
CURLOPT_FOLLOWLOCATION | Follow redirects by recursively returning the "Location: " header from the server. Use CURLOPT_MAXREDIRS to limit the number of redirects. | |
CURLOPT_FORBID_REUSE | Force a connection to close after completion, preventing reuse. | |
CURLOPT_FRESH_CONNECT | Force a new connection instead of using a cached one. | |
CURLOPT_FTP_USE_EPRT | Enable EPRT (or LPRT) commands for FTP downloads. Set to FALSE to disable EPRT and LPRT, using only PORT commands. | |
CURLOPT_FTP_USE_EPSV | Enable EPSV commands before falling back to PASV mode during FTP transfers. Set to FALSE to disable EPSV commands. | |
CURLOPT_FTPAPPEND | Append to the file instead of overwriting it. | |
CURLOPT_FTPASCII | Alias for CURLOPT_TRANSFERTEXT. | |
CURLOPT_FTPLISTONLY | Enable to list only the names of FTP directories. | |
CURLOPT_HEADER | Enable to include header information in the output stream. | |
CURLINFO_HEADER_OUT | Track the request string of the handle. | Available from PHP 5.1.3. The CURLINFO_ prefix is intentional. |
CURLOPT_HTTPGET | Enable to set the HTTP method to GET. Used only if the method has been changed from the default. | |
CURLOPT_HTTPPROXYTUNNEL | Enable tunneling through an HTTP proxy. | |
CURLOPT_MUTE | Enable to reset all cURL parameters to their default values. | |
CURLOPT_NETRC | Access the ~/.netrc file to retrieve username and password information for connecting to remote sites. | |
CURLOPT_NOBODY | Enable to exclude the body part of the HTML output. | |
CURLOPT_NOPROGRESS | When enabled, the progress bar for curl transfers is disabled. This option is enabled by default. Note: <br> <br> PHP automatically sets this option to TRUE. It should only be changed for debugging purposes. | |
CURLOPT_NOSIGNAL | When enabled, all signals sent to php by curl are ignored. This option is enabled by default in SAPI multithreaded transfers. | Added in cURL 7.10. |
CURLOPT_POST | When enabled, a regular POST request is sent, with the type: application/x-www-form-urlencoded, similar to form submission. | |
CURLOPT_PUT | When enabled, allows HTTP to send files. Both CURLOPT_INFILE and CURLOPT_INFILESIZE must be set simultaneously. | |
CURLOPT_RETURNTRANSFER | Returns the information obtained by curl_exec() as a file stream instead of directly outputting it. | |
CURLOPT_SSL_VERIFYPEER | When disabled, cURL will stop verifying the server's certificate. Use the CURLOPT_CAINFO option to set the certificate or the CURLOPT_CAPATH option to set the certificate directory. <br> If CURLOPT_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. Bundled installation since cURL 7.10. |
CURLOPT_TRANSFERTEXT | When enabled, uses ASCII mode for FTP transfers. For LDAP, it retrieves plain text information instead of HTML. On Windows systems, the system does not set STDOUT to binary mode. | |
CURLOPT_UNRESTRICTED_AUTH | Appends username and password information in multiple locations in the header generated by CURLOPT_FOLLOWLOCATION, even if the domain has changed. | |
CURLOPT_UPLOAD | When enabled, allows file uploads. | |
CURLOPT_VERBOSE | When enabled, reports all information, stored in STDERR or specified in CURLOPT_STDERR. |
For the following options, the value should be set to an integer:
Option | Possible value | Notes |
---|---|---|
CURLOPT_BUFFERSIZE | The size of the buffer to read data into during each fetch, but this value is not guaranteed to 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, it waits indefinitely. | |
CURLOPT_CONNECTTIMEOUT_MS | The time to wait for a connection attempt, in milliseconds. If set to 0, it waits indefinitely. | Added in cURL 7.16.2. Available from PHP 5.2.3. |
CURLOPT_DNS_CACHE_TIMEOUT | The time to keep DNS information in memory, default is 120 seconds. | |
CURLOPT_FTPSSLAUTH | FTP authentication method: CURLFTPAUTH_SSL (tries SSL first), CURLFTPAUTH_TLS (tries TLS first), or CURLFTPAUTH_DEFAULT (lets cURL decide). | Added in cURL 7.12.2. |
CURLOPT_HTTP_VERSION | Either CURL_HTTP_VERSION_NONE (default, lets cURL decide which version to use), CURL_HTTP_VERSION_1_0 (forces HTTP/1.0), or CURL_HTTP_VERSION_1_1 (forces HTTP/1.1). | |
CURLOPT_INFILESIZE | Sets the size limit for uploaded files, in bytes. | |
CURLOPT_LOW_SPEED_LIMIT | When the transfer speed is below CURLOPT_LOW_SPEED_LIMIT (bytes/sec), PHP checks if it is too slow based on CURLOPT_LOW_SPEED_TIME to possibly cancel the transfer. | |
CURLOPT_LOW_SPEED_TIME | When the transfer speed is less than CURLOPT_LOW_SPEED_LIMIT (bytes/sec), PHP will determine whether to cancel the transfer due to being too slow based on CURLOPT_LOW_SPEED_TIME. | |
CURLOPT_MAXCONNECTS | The maximum number of allowed connections. Excess connections will be determined to be stopped based on CURLOPT_CLOSEPOLICY. | |
CURLOPT_MAXREDIRS | Specifies the maximum number of HTTP redirects. This option is used in conjunction with CURLOPT_FOLLOWLOCATION. | |
CURLOPT_PORT | Used to specify the connection port. (Optional) | |
CURLOPT_PROTOCOLS | Bitmask of CURLPROTO_* values. If enabled, the bitmask limits the protocols that libcurl can use during the transfer. This allows you to support many protocols when compiling libcurl but restrict the subset that can be used. By default, libcurl will use all supported protocols. See CURLOPT_REDIR_PROTOCOLS. 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_PROXYAUTH | The HTTP proxy connection authentication method. Use the bitmask flags from CURLOPT_HTTPAUTH to set the appropriate options. Only CURLAUTH_BASIC and CURLAUTH_NTLM are currently supported for proxy authentication. | Added in cURL 7.10.7. |
CURLOPT_PROXYPORT | The port of the proxy server. The port can also be set in CURLOPT_PROXY. | |
CURLOPT_PROXYTYPE | Either CURLPROXY_HTTP (default) or CURLPROXY_SOCKS5. | Added in cURL 7.10. |
CURLOPT_REDIR_PROTOCOLS | Bitmask of CURLPROTO_* values. If enabled, the bitmask will limit the protocols that can be used by the transfer thread when CURLOPT_FOLLOWLOCATION is enabled and following a redirect. This allows you to restrict the protocols that can be used during redirects. By default, libcurl will allow all protocols except FILE and SCP. This differs from pre-release versions of 7.19.4 where all supported protocols were followed unconditionally. Refer to CURLOPT_PROTOCOLS for protocol constants. | Added in cURL 7.19.4. |
CURLOPT_RESUME_FROM | Passes a byte offset for resuming a transfer. | |
CURLOPT_SSL_VERIFYHOST | 1 checks if the server SSL certificate contains a common name. 2 checks if the common name exists and matches the provided hostname. | |
CURLOPT_SSLVERSION | The SSL version to use (2 or 3). PHP will automatically detect this value, although manual setting may be required in some cases. | |
CURLOPT_TIMECONDITION | If the page has been modified since the time specified in CURLOPT_TIMEVALUE, use CURL_TIMECOND_IFMODSINCE to return the page. If it has not been modified and CURLOPT_HEADER is true, return a "304 Not Modified" header. If CURLOPT_HEADER is false, use CURL_TIMECOND_IFUNMODSINCE. The default value is CURL_TIMECOND_IFUNMODSINCE. | |
CURLOPT_TIMEOUT | Sets the maximum number of seconds allowed for the cURL execution. | |
CURLOPT_TIMEOUT_MS | Sets the maximum number of milliseconds allowed for the cURL execution. Added in cURL 7.16.2. Available from PHP 5.2.3. | |
CURLOPT_TIMEVALUE | Sets the timestamp to be used with CURLOPT_TIMECONDITION. By default, it uses CURL_TIMECOND_IFMODSINCE. |
For the following options, the value should be set to a string:
Option | Possible value | Note |
---|---|---|
CURLOPT_CAINFO | The filename of a file holding one or more certificates to verify the peer with. This option is only meaningful when used in conjunction with CURLOPT_SSL_VERIFYPEER. | |
CURLOPT_CAPATH | A directory that holds multiple CA certificates. This option is used with CURLOPT_SSL_VERIFYPEER. | |
CURLOPT_COOKIE | The contents of the "Cookie: " header to be used in the HTTP request. Multiple cookies are separated with a semicolon followed by a space (e.g., "fruit=apple; colour=red"). | |
CURLOPT_COOKIEFILE | The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file. | |
CURLOPT_COOKIEJAR | The file to save all internal cookies to when the connection ends. | |
CURLOPT_CUSTOMREQUEST | A custom request method to use instead of "GET" or "HEAD" when doing an HTTP request. This is useful for doing "DELETE" or other, more obscure HTTP requests. Valid values are things like "GET", "POST", "CONNECT" and so on; i.e., do not enter the entire HTTP request. For example, entering "GET /index.html HTTP/1.0\r\n\r\n" is incorrect. Note: <br> <br> Do not use this unless you are sure the server supports the custom request method. | |
CURLOPT_EGDSOCKET | Similar to CURLOPT_RANDOM_FILE, except for an Entropy Gathering Daemon socket. | |
CURLOPT_ENCODING | The contents of the "Accept-Encoding: " header. This enables decoding of the response. Supported encodings are "identity", "deflate", and "gzip". If an empty string, "", is set, a header containing all supported encoding types is sent. Added in cURL 7.10. | |
CURLOPT_FTPPORT | The value which will be used to get the IP address to use for the FTP "POST" instruction. The "POST" instruction tells the remote server to connect to our specified IP address. The string can be a plain IP address, a hostname, a network interface name (under Unix), or just a plain '-' to use the system's default IP address. | |
CURLOPT_INTERFACE | The name of the network interface out going traffic will use. Can be a interface name, an IP address or a host name. | |
CURLOPT_KRB4LEVEL | The KRB4 (Kerberos 4) security level. Any of the following values are valid (in order from least to most powerful): "clear", "safe", "confidential", "private". If the string does not match one of these, "private" is used. Setting this option to NULL disables KRB4 security. KRB4 security only works with FTP transactions. | |
CURLOPT_POSTFIELDS | Sends all data using the "POST" operation in HTTP. To send files, prefix the filename with @ and use the full path. This parameter can be set as a URL-encoded string like 'para1=val1¶2=val2&...' or as an array with field names as keys and field data as values. If the value is an array, the Content-Type header will be set to multipart/form-data. | |
CURLOPT_PROXY | HTTP proxy channel. | |
CURLOPT_PROXYUSERPWD | A string in the format "[username]:[password]" used to connect to the proxy. | |
CURLOPT_RANDOM_FILE | A filename used to generate an SSL random seed. | |
CURLOPT_RANGE | The data range to retrieve in the format "X-Y", where X and Y are optional, measured in bytes. HTTP transfer threads also support multiple ranges separated by commas, like "X-Y,N-M". | |
CURLOPT_REFERER | The content for the "Referer:" header in HTTP requests. | |
CURLOPT_SSL_CIPHER_LIST | A list of SSL ciphers, such as RC4-SHA and TLSv1. | |
CURLOPT_SSLCERT | The filename of a PEM formatted certificate. | |
CURLOPT_SSLCERTPASSWD | The password required for the CURLOPT_SSLCERT certificate. | |
CURLOPT_SSLCERTTYPE | The type of certificate. Supported formats include "PEM" (default), "DER", and "ENG". Added in cURL 7.9.3. | |
CURLOPT_SSLENGINE | The cryptographic engine for the SSL private key specified in CURLOPT_SSLKEY. | |
CURLOPT_SSLENGINE_DEFAULT | The variable used for asymmetric encryption operations. | |
CURLOPT_SSLKEY | The filename containing the SSL private key. | |
CURLOPT_SSLKEYPASSWD | The password for the SSL private key specified in CURLOPT_SSLKEY. Note: Ensure the security of the PHP script as this option contains sensitive password information. | |
CURLOPT_SSLKEYTYPE | The encryption type of the private key specified in CURLOPT_SSLKEY, with supported types being "PEM" (default), "DER", and "ENG". | |
CURLOPT_URL | The URL to fetch, which can also be set in the curl_init() function. | |
CURLOPT_USERAGENT | A string containing the "User-Agent:" header in HTTP requests. | |
CURLOPT_USERPWD | A string in the format "[username]:[password]" required for the connection. |
For the following options, the value should be set as an array:
Option | Optional value | Notes |
---|---|---|
CURLOPT_HTTP200ALIASES | An array of 200 response codes, where codes in the array are considered valid responses, otherwise they are considered errors. Added in cURL 7.10.3. | |
CURLOPT_HTTPHEADER | An array to set HTTP header fields, using an array in the format: array('Content-type: text/plain', 'Content-length: 100') | |
CURLOPT_POSTQUOTE | An array of FTP commands to execute on the server after the FTP request is completed. | |
CURLOPT_QUOTE | An array of FTP commands to execute on the server before the FTP request. |
For the following options, the value should be set as a stream resource (e.g., using fopen()):
Option | Optional value |
---|---|
CURLOPT_FILE | The location for the output file, value is a resource type, defaulting to STDOUT (browser). |
CURLOPT_INFILE | The file location to read from when uploading a file, value is a resource type. |
CURLOPT_STDERR | The location for error output, value is a resource type, replacing the default STDERR. |
CURLOPT_WRITEHEADER | Set the file location for writing header content, the value is a resource type. |
For the following options, the value should be set to a callback function name:
Option | Optional value |
---|---|
CURLOPT_HEADERFUNCTION | Set a callback function that takes 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, returning the size of the written data. |
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 length of the password. 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 data contained. |
CURLOPT_READFUNCTION | Callback function name. The function should take three parameters. The first is the cURL resource; the second is the stream resource passed to cURL via the CURLOPT_INFILE option; 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 amount of data (the third parameter). Usually read from the passed stream resource. Return an empty string as an EOF (end of file) signal. |
CURLOPT_WRITEFUNCTION | Callback function name. The function should take two parameters. The first is the cURL resource; the second is the string of data to be written. The data must be saved within the function. The function must return the exact number of bytes of the data to be written, otherwise, the transmission will be interrupted by an error. |
Return Value
Returns TRUE on success, or FALSE on failure.
Changelog
Version | Description |
---|---|
5.2.10 | Introduced CURLOPT_PROTOCOLS, and CURLOPT_REDIR_PROTOCOLS. |
5.1.0 | Introduced CURLOPT_AUTOREFERER, CURLOPT_BINARYTRANSFER, CURLOPT_FTPSSLAUTH, CURLOPT_PROXYAUTH, and CURLOPT_TIMECONDITION. |
5.0.0 | Introduced CURLOPT_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 webpage
<?php
// Create a new cURL resource
$ch = curl_init();
// Set URL and corresponding options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);
// Fetch the URL and pass it to the browser
curl_exec($ch);
// Close cURL resource, and free up system resources
curl_close($ch);
?>
Upload file 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
)
)
Comments
Passing an array to CURLOPT_POSTFIELDS will cause the data to be encoded as multipart/form-data, whereas passing a URL-encoded string will result in the data being encoded as application/x-www-form-urlencoded.