English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP curl_setopt() function usage and example

PHP CURL Reference Manual

(PHP 4 >= 4.0.2, PHP 5)

curl_setopt — Set a CURL transfer option.

syntax

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

Set an option for the given CURL session handle.

parameter

ch

The CURL handle returned by curl_init().

option

The CURLOPT_XXX option that needs to be set.

value

The value set on the option option.

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

OptionOptionalvalueValueNote
CURLOPT_AUTOREFERERWhen based onLocation:When redirecting, automatically set the header inReferer:information.
CURLOPT_BINARYTRANSFERWhen enabledCURLOPT_RETURNTRANSFERwhen, return the original (Raw) output.
CURLOPT_COOKIESESSIONWhen enabled, curl will only pass a session cookie, ignoring other cookies. By default, CURL will return all cookies to the server. A session cookie is a cookie that exists to determine whether the server's session is valid.
CURLOPT_CRLFWhen enabled, it will convert Unix's newline to carriage return newline.
CURLOPT_DNS_USE_GLOBAL_CACHEWhen enabled, it will enable a global DNS cache, this option is thread-safe, and is enabled by default.
CURLOPT_FAILONERRORDisplay the HTTP status code, the default behavior is to ignore the numbers less than or equal to400 HTTP information.
CURLOPT_FILETIMEWhen enabled, it will attempt to modify the information in the remote document. The result information will be passed through the curl_getinfo() function'sCURLINFO_FILETIMEoption return.            curl_getinfo().
CURLOPT_FOLLOWLOCATIONWhen enabled, it will return the"Location: "Return recursively to the server in the header, usingCURLOPT_MAXREDIRSThe number of recursive returns can be limited.
CURLOPT_FORBID_REUSEForcefully disconnect after completing the interaction, and cannot be reused.
CURLOPT_FRESH_CONNECTForce a new connection to be obtained instead of the connection in the cache.
CURLOPT_FTP_USE_EPRTWhen enabled, use the EPRT (or LPRT) command when downloading FTP. Set toFALSEWhen disabled, EPRT and LPRT are disabled, and the PORT command is used            only.
CURLOPT_FTP_USE_EPSVWhen enabled, it first tries the EPSV command before reverting to PASV mode during FTP transmission. Set toFALSEDisable the EPSV command.
CURLOPT_FTPAPPENDWhen enabled, appends to the file instead of overwriting it.
CURLOPT_FTPASCIICURLOPT_TRANSFERTEXTis an alias.
CURLOPT_FTPLISTONLYWhen enabled, only lists the names of the FTP directories.
CURLOPT_HEADERWhen enabled, outputs the information of the header file as a data stream.
CURLINFO_HEADER_OUTWhen enabled, traces the request string of the handle.From PHP 5.1.3 The time to wait for a connection attempt, in milliseconds. If set to 0, it will wait indefinitely.CURLINFO_The prefix is intentional.
CURLOPT_HTTPGETWhen enabled, sets the HTTP method to GET, because GET is the default, so it is only used when it is modified.
CURLOPT_HTTPPROXYTUNNELWhen enabled, transmits through HTTP proxy.
CURLOPT_MUTEWhen enabled, restores all modified parameters in the CURL function to default values.
CURLOPT_NETRCAfter the connection is established, access ~/Connect to a remote site using the .netrc file to obtain username and password information.
CURLOPT_NOBODYWhen enabled, does not output the BODY part of HTML.
CURLOPT_NOPROGRESS

When enabled, closes the progress bar of curl transmission, and the default setting for this option is enabled.

Note:

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


CURLOPT_NOSIGNALWhen enabled, ignores all signals passed to PHP by curl. This option is enabled by default in SAPI multi-threaded transmission.CURL 7.10is added.
CURLOPT_POSTWhen enabled, it sends a regular POST request of type:application/x-www-form-urlencoded, just like form submission.
CURLOPT_PUTWhen enabled, allows HTTP to send files, and it must be set at the same timeCURLOPT_INFILEand).
CURLOPT_RETURNTRANSFERReturns the information obtained by curl_exec() in the form of a file stream instead of direct output.
CURLOPT_SSL_VERIFYPEERAfter disabling, CURL will terminate verification from the server side. UseCURLOPT_CAINFOOption to set the certificate usageCURLOPT_CAPATHOption to set the certificate directory            IfCURLOPT_SSL_VERIFYPEER(The default value is2) is enabled,CURLOPT_SSL_VERIFYHOSTNeeds to be set toTRUEOtherwise set toFALSE.Since CURL 7.10Starts with the default ofTRUE. From CURL 7.10Start the default binding installation.
CURLOPT_TRANSFERTEXTAfter enabling, FTP transmission uses ASCII mode. For LDAP, it retrieves plain text information instead of HTML. On Windows systems, the system will not treatSTDOUT设置成binary模式。
CURLOPT_UNRESTRICTED_AUTHSet to binary mode.CURLOPT_FOLLOWLOCATIONWhen using
Continuously append username and password information to the multiple locations in the generated header, even if the domain has changed.CURLOPT_UPLOAD
Enable after allowing file upload.CURLOPT_VERBOSESTDERREnable reporting of all information, stored inCURLOPT_STDERROr specified

.

OptionOptionalvalueValueNote
CURLOPT_BUFFERSIZEFor the optional parameters of the following options, the value should be set to an integer type:In CURL 7.10is added.
CURLOPT_CLOSEPOLICYThe size of the data read into the cache each time, but it is not guaranteed that this value will be filled every time.
It is not CURLCLOSEPOLICY_LEAST_RECENTLY_USED or CURLCLOSEPOLICY_OLDEST, there are also three other CURLCLOSEPOLICY, but CURL does not support them temporarily.CURLOPT_CONNECTTIMEOUT
The time to wait before initiating a connection, if set to 0, it will wait indefinitely.CURLOPT_CONNECTTIMEOUT_MSIn CURL 7.16.2added. From PHP 5.2.3The time to wait for a connection attempt, in milliseconds. If set to 0, it will wait indefinitely.
available.CURLOPT_DNS_CACHE_TIMEOUT12Set the time to save DNS information in memory, the default is
CURLOPT_FTPSSLAUTH0 seconds.FTP authentication method: CURLFTPAUTH_SSL(First try SSL), CURLFTPAUTH_TLS(First try TLS) or CURLFTPAUTH_DEFAULTIn CURL 7.12.2is added.
(Let CURL decide automatically).CURLOPT_HTTP_VERSION CURL_HTTP_VERSION_NONE.0) or1(Default value, let CURL decide which version to use), _/1_0.0) or1CURL_HTTP_VERSION_1 _/1.1(Force to use HTTP
)CURLOPT_INFILESIZE
When the transfer speed is less thanSet the size limit of the uploaded file, in bytes (byte) as the unit.When the transfer speed is less thanCURLOPT_LOW_SPEED_LIMIT/bytessec), PHP willby
sec), PHP willSet the size limit of the uploaded file, in bytes (byte) as the unit.When the transfer speed is less thanCURLOPT_LOW_SPEED_LIMIT/bytessec), PHP willby
CURLOPT_MAXCONNECTSThe maximum number of allowed connections, if exceeded, it will be judged whether to cancel the transfer due to being too slow.CURLOPT_CLOSEPOLICYDecide which connections should stop.
CURLOPT_MAXREDIRSSpecify the maximum number of HTTP redirects, this option is related toCURLOPT_FOLLOWLOCATIONused together.
CURLOPT_PORTUsed to specify the connection port. (Optional)
CURLOPT_PROTOCOLSCURLPROTO_*bit field indication. If enabled, the bit field value will limit the protocols that libcurl can use during transmission. This will allow you to support many protocols when compiling libcurl, but limit them to only the subset that is allowed to be used. By default, libcurl will use all the protocols it supports. SeeCURLOPT_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_ALLIn CURL 7.19.4is added.
CURLOPT_PROTOCOLSCURLPROTO_*bit field indication. If enabled, the bit field value will limit the protocols that libcurl can use during transmission. This will allow you to support many protocols when compiling libcurl, but limit them to only the subset that is allowed to be used. By default, libcurl will use all the protocols it supports. SeeCURLOPT_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_ALLIn CURL 7.19.4is added.
CURLOPT_PROXYAUTHHTTP proxy connection authentication methods. Used inCURLOPT_HTTPAUTHbit field flags to set the corresponding options. For proxy authentication onlyCURLAUTH_BASICandCURLAUTH_NTLMis currently supported.In CURL 7.10.7is added.
CURLOPT_PROXYPORTThe port of the proxy server. The port can also be set inCURLOPT_PROXYto be set.
CURLOPT_PROXYTYPEis notCURLPROXY_HTTP (default value) isCURLPROXY_SOCKS5.In CURL 7.10is added.
CURLOPT_REDIR_PROTOCOLSCURLPROTO_*The bit field values in.CURLOPT_FOLLOWLOCATIONThe protocols that can be used when following a redirect can be set when enabled. This will allow you to limit the subset of protocols allowed during redirection to the default libcurl will allow all protocols except FILE and SCP. This and7.19.4Unconditionally follow all supported protocols in pre-release versions. For protocol constants, please refer toCURLOPT_PROTOCOLS.In CURL 7.19.4is added.
CURLOPT_RESUME_FROMpass a byte offset when resuming transmission (used for resuming downloads).
CURLOPT_SSL_VERIFYHOST1 Check if there is a common name (common name) in the server SSL certificate. Translator's note: The common name (Common Name) generally refers to the domain (domain) or subdomain (sub domain) where you will apply for an SSL certificate.2 check if the common name exists and if it matches the provided hostname.
CURLOPT_SSLVERSIONthe SSL version used (2 or 3). By default, PHP will detect this value itself, although in some cases it may need to be set manually.
CURLOPT_TIMECONDITIONIf inCURLOPT_TIMEVALUEhas been edited after a specified time,CURL_TIMECOND_IFMODSINCEif the page has not been modified andCURLOPT_HEADERreturns a page if it is true,"304 Not Modified"The header,    CURLOPT_HEADERif false, then useCURL_TIMECOND_IFUNMODSINCE, the default value isCURL_TIMECOND_IFUNMODSINCE.
CURLOPT_TIMEOUTset the maximum number of seconds allowed for CURL to execute.
CURLOPT_TIMEOUT_MSset the maximum number of milliseconds allowed for CURL to execute.In CURL 7.16.2added. From PHP 5.2.3can be used starting from.
CURLOPT_TIMEVALUEset aCURLOPT_TIMECONDITIONtimestamp used, by default usingCURL_TIMECOND_IFMODSINCE.

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

OptionOptionalvalueValueNote
CURLOPT_CAINFOa directory containing1filenames of one or more certificates used to verify the server. This parameter is only meaningful when used withCURLOPT_SSL_VERIFYPEER.
CURLOPT_CAPATHa directory containing multiple CA certificates. This option is meaningful only when used withCURLOPT_SSL_VERIFYPEERused together.
CURLOPT_COOKIEset in the HTTP request"Cookie: "parts of the content. Multiple cookies are separated by semicolons, followed by a space (for example, "fruit=apple; colour=red).
CURLOPT_COOKIEFILEThe filename containing cookie data, the format of the cookie file can be Netscape format, or just store pure HTTP header information in the file.
CURLOPT_COOKIEJARthe file to save cookie information after the connection is closed.
CURLOPT_CUSTOMREQUEST

using a custom request information instead of"GET"or"HEAD"as an HTTP request. This is for executing"DELETE" or other more concealed HTTP requests. Valid values include"GET"}"POST"}"CONNECT"etc. That is, do not enter the entire HTTP request here. For example, enter"GET" /index.html HTTP/1.0\r\n\r\n"is incorrect.

Note:

Do not use it before determining that the server supports this custom request method.


CURLOPT_EGDSOCKETSimilarCURLOPT_RANDOM_FILE, except for an Entropy Gathering Daemon socket.
CURLOPT_ENCODINGin the HTTP request header"Accept"-Encoding: "value. Supported encodings include"identity"}"deflate"and"gzip". If it is an empty string"", the request header will send all supported encoding types.In CURL 7.10is added.
CURLOPT_FTPPORTThis 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, hostname, a network interface name (on UNIX), or just a-'to use the default IP address.
CURLOPT_INTERFACENetwork interface name, which can be an interface name, IP address, or a hostname.
CURLOPT_KRB4LEVELKRB4 (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, "private" will be used."private". This option is set toNULLwill disable KRB4 Secure authentication. Currently KRB4 Secure authentication can only be used for FTP transfers.
CURLOPT_POSTFIELDSAll data is sent using the "POST" operation in the HTTP protocol. To send a file, add@prefix and use the full path. This parameter can be represented by a string after urlencoding similar to'para1=val1¶2=val2&...'or use an array with field names as keys and field data as values. Ifvalueis an array,Content-TypeThe header will be set tomultipart/form-data.
CURLOPT_PROXYHTTP proxy channel.
CURLOPT_PROXYUSERPWDA filename used to connect to a proxy."[username]:[password]"formatted string.
CURLOPT_RANDOM_FILEA filename used to generate SSL random number seeds.
CURLOPT_RANGEwith"X-Y"in the form, where X and Y are optional data range options, in bytes. HTTP transmission threads also support several such repeated items separated by commas, such as"X-Y,N-M".
CURLOPT_REFERERin the HTTP request header"Referer: "content.
CURLOPT_SSL_CIPHER_LISTA list of SSL encryption algorithms. For exampleRC4-SHAandTLSv1are all available encryption lists.
CURLOPT_SSLCERTA filename containing a PEM format certificate.
CURLOPT_SSLCERTPASSWDUseCURLOPT_SSLCERTThe password required for the certificate.
CURLOPT_SSLCERTTYPEThe type of certificate. Supported formats include"PEM" (Default value), "DER"and"ENG".In CURL 7.9.3is added.
CURLOPT_SSLENGINEThe variable used toCURLOPT_SSLKEYThe variable of the SSL private key encryption engine specified in
CURLOPT_SSLENGINE_DEFAULTThe variable used for asymmetric encryption operations.
CURLOPT_SSLKEYThe filename containing the SSL private key.
CURLOPT_SSLKEYPASSWD

is specified.CURLOPT_SSLKEYThe password of the SSL private key specified in

Note:

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


CURLOPT_SSLKEYTYPECURLOPT_SSLKEYThe encryption type specified in the private key specified in"PEM"(Default value),"DER"and"ENG".
CURLOPT_URLThe URL address to be accessed, can also be set in the curl_init() function.
CURLOPT_USERAGENTInclude a"User-Agent: "The string of the header.
CURLOPT_USERPWDPass the username and password required for the connection, formatted as:"[username]:[password]".

For the following optional parameters of these options, the value should be set to an array:

OptionOptionalvalueValueNote
CURLOPT_HTTP200ALIASES200 response code array, the response codes in the array are considered correct responses, otherwise they are considered incorrect.In CURL 7.10.3is added.
CURLOPT_HTTPHEADERAn array used to set HTTP header fields. Set the array in the following form:                       array('Content-type: text/plain', 'Content-length: 100')
CURLOPT_POSTQUOTEA set of FTP commands executed on the server after the FTP request is executed.
CURLOPT_QUOTEA set of FTP commands executed on the server before the FTP request.

For the following optional parameters of these options, the value should be set to a stream resource (for example, using fopen()):

OptionOptionalvalueValue
CURLOPT_FILESet the output file location, the value is a resource type, the default isSTDOUT (Browser).
CURLOPT_INFILEThe file address to be read when uploading a file, the value is a resource type.
CURLOPT_STDERRSet an error output address, the value is a resource type, replacing the defaultSTDERR.
CURLOPT_WRITEHEADERSet the file address for writing the header part, the value is a resource type.

For the optional parameters of the following options, the value should be set to a callback function name:

OptionOptionalvalueValue
CURLOPT_HEADERFUNCTIONSet a callback function with two parameters, the first is the CURL resource handle, and the second is the output header data. The output of the header data must depend on this function, and return the size of the data written.
CURLOPT_PASSWDFUNCTIONSet a callback function with three parameters, the first is the CURL resource handle, the second is a password prompt, and the third parameter is the maximum allowable length of the password. Return the value of the password.
CURLOPT_PROGRESSFUNCTIONSet 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 containing.
CURLOPT_READFUNCTIONCallback function name. This function should accept three parameters. The first is the CURL resource; the second is the data passed through the option CURLOPT_INFILE The stream resource passed to CURL; the third parameter is the maximum number of data that can be read. Back The callback function must return a string, the length of which is less than or equal to the amount of data requested (the third parameter). Generally from the input stream Resource read. Return an empty string as EOF(End of file) Signal.
CURLOPT_WRITEFUNCTIONCallback function name. This function should accept two parameters. The first is the CURL resource; the second is the data string to be written. Numbers The data must be saved within the function. The function must return the exact number of bytes written as input, otherwise the transfer will be interrupted by an error. Break.

Return Value

Returns TRUE on success, or FALSE on failure.

Update Log

VersionDescription
5.2.10Introduction CURLOPT_PROTOCOLS, andCURLOPT_REDIR_PROTOCOLS.
5.1.0Introduction CURLOPT_AUTOREFERER,CURLOPT_BINARYTRANSFER,CURLOPT_FTPSSLAUTH,CURLOPT_PROXYAUTH, andCURLOPT_TIMECONDITION.
5.0.0Introduction CURLOPT_FTP_USE_EPRT,CURLOPT_NOSIGNAL,CURLOPT_UNRESTRICTED_AUTH,CURLOPT_BUFFERSIZE,CURLOPT_HTTPAUTH,CURLOPT_PROXYPORT,CURLOPT_PROXYTYPE,CURLOPT_SSLCERTTYPE, andCURLOPT_HTTP200ALIASES.

Online Example

Initialize a new CURL session and get a web page

<?php
// Create a new CURL resource
$ch = curl_init();
// Set the URL and corresponding options
curl_setopt($ch, CURLOPT_URL, "http://www.oldtoolbag.com/");
curl_setopt($ch, CURLOPT_HEADER, false);
// Fetch the URL and pass it to the browser
curl_exec($ch);
//Close the CURL resource and release the system resources
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 output result of the above example is as follows:

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

Comment

Pass an array to CURLOPT_POSTFIELDS, and CURL will encode the data into multipart/form-data, and then pass a URL-When encoded strings, the data will be encoded into application/x-www-form-urlencoded.

PHP CURL Reference Manual