PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

curl_version> <curl_setopt_array
Last updated: Fri, 26 Sep 2008

view this page in

curl_setopt

(PHP 4 >= 4.0.2, PHP 5)

curl_setoptSet an option for a cURL transfer

Description

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

Sets an option on the given cURL session handle.

Parameters

ch

A cURL handle returned by curl_init().

option

The CURLOPT_XXX option to set.

value

The value to be set on option .

value should be a bool for the following values of the option parameter:

Option Set value to Notes
CURLOPT_AUTOREFERER TRUE to automatically set the Referer: field in requests where it follows a Location: redirect. Available since PHP 5.1.0.
CURLOPT_BINARYTRANSFER TRUE to return the raw output when CURLOPT_RETURNTRANSFER is used.
CURLOPT_COOKIESESSION TRUE to mark this as a new cookie "session". It will force libcurl to ignore all cookies it is about to load that are "session cookies" from the previous session. By default, libcurl always stores and loads all cookies, independent if they are session cookies are not. Session cookies are cookies without expiry date and they are meant to be alive and existing for this "session" only. Available since PHP 5.1.0.
CURLOPT_CRLF TRUE to convert Unix newlines to CRLF newlines on transfers.
CURLOPT_DNS_USE_GLOBAL_CACHE TRUE to use a global DNS cache. This option is not thread-safe and is enabled by default.
CURLOPT_FAILONERROR TRUE to fail silently if the HTTP code returned is greater than or equal to 400. The default behavior is to return the page normally, ignoring the code.
CURLOPT_FILETIME TRUE to attempt to retrieve the modification date of the remote document. This value can be retrieved using the CURLINFO_FILETIME option with curl_getinfo().
CURLOPT_FOLLOWLOCATION TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).
CURLOPT_FORBID_REUSE TRUE to force the connection to explicitly close when it has finished processing, and not be pooled for reuse.
CURLOPT_FRESH_CONNECT TRUE to force the use of a new connection instead of a cached one.
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 TRUE to include the header in the output.
CURLOPT_HTTPGET TRUE to reset the HTTP request method to GET. Since GET is the default, this is only necessary if the request method has been changed.
CURLOPT_HTTPPROXYTUNNEL TRUE to tunnel through a given HTTP proxy.
CURLOPT_MUTE TRUE to be completely silent with regards to the cURL functions.
CURLOPT_NETRC TRUE to scan the ~/.netrc file to find a username and password for the remote site that a connection is being established with.
CURLOPT_NOBODY TRUE to exclude the body from the output.
CURLOPT_NOPROGRESS

TRUE to disable the progress meter for cURL transfers.

Note: PHP automatically sets this option to TRUE, this should only be changed for debugging purposes.

CURLOPT_NOSIGNAL TRUE to ignore any cURL function that causes a signal to be sent to the PHP process. This is turned on by default in multi-threaded SAPIs so timeout options can still be used. Added in cURL 7.10 and PHP 5.0.0.
CURLOPT_POST TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.
CURLOPT_PUT TRUE to HTTP PUT a file. The file to PUT must be set with CURLOPT_INFILE and CURLOPT_INFILESIZE.
CURLOPT_RETURNTRANSFER TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out 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 TRUE to keep sending the username and password when following locations (using CURLOPT_FOLLOWLOCATION), even when the hostname has changed. Added in PHP 5.0.0.
CURLOPT_UPLOAD TRUE to prepare for an upload.
CURLOPT_VERBOSE TRUE to output verbose information. Writes output to STDERR, or the file specified using CURLOPT_STDERR.

value should be an integer for the following values of the option parameter:

Option Set value to Notes
CURLOPT_BUFFERSIZE The size of the buffer to use for each read. There is no guarantee this request will be fulfilled, however. Added in cURL 7.10 and PHP 5.0.0.
CURLOPT_CLOSEPOLICY Either CURLCLOSEPOLICY_LEAST_RECENTLY_USED or CURLCLOSEPOLICY_OLDEST . There are three other CURLCLOSEPOLICY_ constants, but cURL does not support them yet.
CURLOPT_CONNECTTIMEOUT The number of seconds to wait whilst trying to connect. Use 0 to wait indefinitely.
CURLOPT_DNS_CACHE_TIMEOUT The number of seconds to keep DNS entries in memory. This option is set to 120 (2 minutes) by default.
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). Added in cURL 7.12.2 and PHP 5.1.0.
CURLOPT_HTTP_VERSION 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_HTTPAUTH

The HTTP authentication method(s) to use. The options are: CURLAUTH_BASIC , CURLAUTH_DIGEST , CURLAUTH_GSSNEGOTIATE , CURLAUTH_NTLM , CURLAUTH_ANY , and CURLAUTH_ANYSAFE .

The bitwise | (or) operator can be used to combine more than one method. If this is done, cURL will poll the server to see what methods it supports and pick the best one.

CURLAUTH_ANY is an alias for CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

CURLAUTH_ANYSAFE is an alias for CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

Added in PHP 5.0.0.
CURLOPT_INFILESIZE The expected size, in bytes, of the file when uploading a file to a remote site.
CURLOPT_LOW_SPEED_LIMIT The transfer speed, in bytes per second, that the transfer should be below during CURLOPT_LOW_SPEED_TIME seconds for PHP to consider the transfer too slow and abort.
CURLOPT_LOW_SPEED_TIME The number of seconds the transfer should be below CURLOPT_LOW_SPEED_LIMIT for PHP to consider the transfer too slow and abort.
CURLOPT_MAXCONNECTS The maximum amount of persistent connections that are allowed. When the limit is reached, CURLOPT_CLOSEPOLICY is used to determine which connection to close.
CURLOPT_MAXREDIRS The maximum amount of HTTP redirections to follow. Use this option alongside CURLOPT_FOLLOWLOCATION.
CURLOPT_PORT An alternative port number to connect to.
CURLOPT_PROXYAUTH The HTTP authentication method(s) to use for the proxy connection. Use the same bitmasks as described in CURLOPT_HTTPAUTH. For proxy authentication, only CURLAUTH_BASIC and CURLAUTH_NTLM are currently supported. Added in cURL 7.10.7 and PHP 5.1.0.
CURLOPT_PROXYPORT The port number of the proxy to connect to. This port number can also be set in CURLOPT_PROXY. Added in PHP 5.0.0.
CURLOPT_PROXYTYPE Either CURLPROXY_HTTP (default) or CURLPROXY_SOCKS5 . Added in cURL 7.10 and PHP 5.0.0.
CURLOPT_RESUME_FROM The offset, in bytes, to resume a transfer from.
CURLOPT_SSL_VERIFYHOST 1 to check the existence of a common name in the SSL peer certificate. 2 to check the existence of a common name and also verify that it matches the hostname provided.
CURLOPT_SSLVERSION The SSL version (2 or 3) to use. By default PHP will try to determine this itself, although in some cases this must be set manually.
CURLOPT_TIMECONDITION How CURLOPT_TIMEVALUE is treated. Use CURL_TIMECOND_IFMODSINCE to return the page only if it has been modified since the time specified in CURLOPT_TIMEVALUE. If it hasn't been modified, a "304 Not Modified" header will be returned assuming CURLOPT_HEADER is TRUE. Use CURL_TIMECOND_ISUNMODSINCE for the reverse effect. CURL_TIMECOND_IFMODSINCE is the default. Added in PHP 5.1.0.
CURLOPT_TIMEOUT The maximum number of seconds to allow cURL functions to execute.
CURLOPT_TIMEVALUE The time in seconds since January 1st, 1970. The time will be used by CURLOPT_TIMECONDITION. By default, CURL_TIMECOND_IFMODSINCE is used.

value should be a string for the following values of the option parameter:

Option Set value to Notes
CURLOPT_CAINFO The name of a file holding one or more certificates to verify the peer with. This only makes sense when used in combination with CURLOPT_SSL_VERIFYPEER.
CURLOPT_CAPATH A directory that holds multiple CA certificates. Use this option alongside CURLOPT_SSL_VERIFYPEER.
CURLOPT_COOKIE The contents of the "Set-Cookie: " header to be used in the HTTP request.
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 name of a file to save all internal cookies to when the connection closes.
CURLOPT_CUSTOMREQUEST

A custom request method to use instead of "GET" or "HEAD" when doing a 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 a whole HTTP request line here. For instance, entering "GET /index.html HTTP/1.0\r\n\r\n" would be incorrect.

Note: Don't do this without making sure the server supports the custom request method first.

CURLOPT_EGDSOCKET Like CURLOPT_RANDOM_FILE, except a filename to 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 may be a plain IP address, a hostname, a network interface name (under Unix), or just a plain '-' to use the systems default IP address.
CURLOPT_INTERFACE The name of the outgoing network interface to use. This can be an interface name, an IP address or a host name.
CURLOPT_KRB4LEVEL The KRB4 (Kerberos 4) security level. Any of the following values (in order from least to most powerful) are valid: "clear", "safe", "confidential", "private".. If the string does not match one of these, "private" is used. Setting this option to NULL will disable KRB4 security. Currently KRB4 security only works with FTP transactions.
CURLOPT_POSTFIELDS The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path.
CURLOPT_PROXY The HTTP proxy to tunnel requests through.
CURLOPT_PROXYUSERPWD A username and password formatted as "[username]:[password]" to use for the connection to the proxy.
CURLOPT_RANDOM_FILE A filename to be used to seed the random number generator for SSL.
CURLOPT_RANGE Range(s) of data to retrieve in the format "X-Y" where X or Y are optional. HTTP transfers also support several intervals, separated with commas in the format "X-Y,N-M".
CURLOPT_REFERER The contents of the "Referer: " header to be used in a HTTP request.
CURLOPT_SSL_CIPHER_LIST A list of ciphers to use for SSL. For example, RC4-SHA and TLSv1 are valid cipher lists.
CURLOPT_SSLCERT The name of a file containing a PEM formatted certificate.
CURLOPT_SSLCERTPASSWD The password required to use the CURLOPT_SSLCERT certificate.
CURLOPT_SSLCERTTYPE The format of the certificate. Supported formats are "PEM" (default), "DER", and "ENG". Added in cURL 7.9.3 and PHP 5.0.0.
CURLOPT_SSLENGINE The identifier for the crypto engine of the private SSL key specified in CURLOPT_SSLKEY.
CURLOPT_SSLENGINE_DEFAULT The identifier for the crypto engine used for asymmetric crypto operations.
CURLOPT_SSLKEY The name of a file containing a private SSL key.
CURLOPT_SSLKEYPASSWD

The secret password needed to use the private SSL key specified in CURLOPT_SSLKEY.

Note: Since this option contains a sensitive password, remember to keep the PHP script it is contained within safe.

CURLOPT_SSLKEYTYPE The key type of the private SSL key specified in CURLOPT_SSLKEY. Supported key types are "PEM" (default), "DER", and "ENG".
CURLOPT_URL The URL to fetch. This can also be set when initializing a session with curl_init().
CURLOPT_USERAGENT The contents of the "User-Agent: " header to be used in a HTTP request.
CURLOPT_USERPWD A username and password formatted as "[username]:[password]" to use for the connection.

value should be an array for the following values of the option parameter:

Option Set value to Notes
CURLOPT_HTTP200ALIASES An array of HTTP 200 responses that will be treated as valid responses and not as errors. Added in cURL 7.10.3 and PHP 5.0.0.
CURLOPT_HTTPHEADER An array of HTTP header fields to set.
CURLOPT_POSTQUOTE An array of FTP commands to execute on the server after the FTP request has been performed.
CURLOPT_QUOTE An array of FTP commands to execute on the server prior to the FTP request.

value should be a stream resource (using fopen(), for example) for the following values of the option parameter:

Option Set value to Notes
CURLOPT_FILE The file that the transfer should be written to. The default is STDOUT (the browser window).
CURLOPT_INFILE The file that the transfer should be read from when uploading.
CURLOPT_STDERR An alternative location to output errors to instead of STDERR.
CURLOPT_WRITEHEADER The file that the header part of the transfer is written to.

value should be a string that is the name of a valid callback function for the following values of the option parameter:

Option Set value to Notes
CURLOPT_HEADERFUNCTION The name of a callback function where the callback function takes two parameters. The first is the cURL resource, the second is a string with the header data to be written. The header data must be written when using this callback function. Return the number of bytes written.
CURLOPT_PASSWDFUNCTION The name of a callback function where the callback function takes three parameters. The first is the cURL resource, the second is a string containing a password prompt, and the third is the maximum password length. Return the string containing the password.
CURLOPT_READFUNCTION The name of a callback function where the callback function takes two parameters. The first is the cURL resource, and the second is a string with the data to be read. The data must be read by using this callback function. Return the number of bytes read. Return 0 to signal EOF.
CURLOPT_WRITEFUNCTION The name of a callback function where the callback function takes two parameters. The first is the cURL resource, and the second is a string with the data to be written. The data must be written by using this callback function. Must return the exact number of bytes written or this will fail.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Initializing a new cURL session and fetching a web page

<?php
// create a new cURL resource
$ch curl_init();

// set URL and other appropriate options
curl_setopt($chCURLOPT_URL"http://www.example.com/");
curl_setopt($chCURLOPT_HEADERfalse);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

Example #2 Uploading file

<?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($chCURLOPT_URL'http://localhost/upload.php');
curl_setopt($chCURLOPT_POST1);
curl_setopt($chCURLOPT_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
        )

)



curl_version> <curl_setopt_array
Last updated: Fri, 26 Sep 2008
 
add a note add a note User Contributed Notes
curl_setopt
adamplumb at gmail dot com
26-Sep-2008 09:10
In response to rkirilow's post, where he said to set the option CURLOPT_FILE, that should really be CURLOPT_COOKIEFILE.  I was bitten by this issue myself with code that previously worked for logging into a website and posting a form.  However, at some point the code just stopped working, and I eventually found that I needed to set this option to /dev/null for it to work.
OPALA
26-Sep-2008 03:37
To fetch (or submit data to) multiple pages during one session,use this:

<?php
$ch
= curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

curl_setopt($ch, CURLOPT_URL, 'http://site.com/page1.php');
$result1 = curl_exec($ch);

curl_setopt($ch, CURLOPT_URL, 'http://site.com/page2.php');
$result2 = curl_exec($ch);

curl_close($ch);
?>
rkirilow at gmail dot com
16-Sep-2008 04:34
Some of you may noticed that curl is not transferring cookies between sequent calls to a host. This is because you must activate curl`s "cookie parser". That is achieved using an external file like this:
<?php
curl_setopt
(CURLOPT_FILE, '/tmp/cookies_file');
?>
If you don`t need to read any cookies but you still want the "cookie parser" use the same code but with dummy file with no data like '/dev/null', that way curl is storing cookies internaly per curl_handle:
<?php
curl_setopt
(CURLOPT_FILE, '/dev/null');
?>
AmBAr Amarelo
07-Sep-2008 05:51
Like eion said before (http://br.php.net/manual/ro/function.curl-setopt.php#71313), the function CURLOPT_FOLLOWLOCATION don't will work when OPEN_BASEDIR is ON (or SAFE_MODE is ON).
he created a CURLOPT_FOLLOWLOCATION function alternative named: curl_redir_exec()

Well, this function have a little error on line that contains:
list($header, $data) = explode("\n\n", $data, 2);
do you have replace for:
list($header, $data) = explode("\r\n", $data, 2);

note the '\n\n' cause this error, so just replace for '\r\n'.

Thanks Eion for your curl_redir_exec() Function :)
George
23-Aug-2008 08:14
If you set CURLOPT_RESUME_FROM to resume the file, and then reuse the same Curl handle to download another file, you must reset the resume status by calling curl_setopt( $ch, CURLOPT_RESUME_FROM, 0 ). It will not reset, and will apply to all subsequent transfers even if the URL is the same.
w dot danford at electronics-software dot com
13-Aug-2008 01:12
Just a small detail I too easily overlooked.
<?php
/*  If you set:  */
curl_setopt ($ch, CURLOPT_POST, 1);
/* then you must have the data: */
curl_setopt ($ch, CURLOPT_POSTFIELDS, $PostData);
?>
I found with only the CURLOPT_POST set (from copy, paste editing of course) cookies were not getting sent with CURLOPT_COOKIE.  Just something subtle to watch out for.
fred at themancan dot com
06-Aug-2008 07:28
What encoding will a given HTTP POST request use?

The answer is easy -- passing an array to CURLOPT_POSTFIELDS results in  multipart/form-data:

<?php
curl_setopt
(CURLOPT_POSTFIELDS, array('field1' => 'value'));
?>

Passing a URL-encoded string will result in application/x-www-form-urlencoded:

<?php
curl_setopt
(CURLOPT_POSTFIELDS, array('field1=value&field2=value2'));
?>

I ran across this when integrating with both a warehouse system and an email system; neither would accept multipart/form-data, but both happily accepted application/x-www-form-urlencoded.
jID
05-Aug-2008 07:56
if you use
<?php
curl_setopt
($ch, CURLOPT_INTERFACE, "XXX.XXX.XXX.XXX");
?>
to specify IP adress for request, sometimes you need to get list of all your IP's.

ifconfig command will output something like:

rl0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
    options=8<VLAN_MTU>
    inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
    inet 78.24.XXX.XXX netmask 0xffffffff broadcast 78.24.XXX.XXX
    inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
    inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
    inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
    inet 78.24.XXX.XXX netmask 0xffffffff broadcast 78.24.XXX.XXX
    inet 78.24.XXX.XXX netmask 0xffffffff broadcast 78.24.XXX.XXX
    ether XX:XX:XX:XX:XX:XX
    media: Ethernet autoselect (100baseTX <full-duplex>)
    status: active
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
tun0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1500
    Opened by PID 564
tun1: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1500
    Opened by PID 565
    Opened by PID 565

My solution for FreeBSD 6 and PHP 5 was:
<?php
  ob_start
();
 
$ips=array();
 
$ifconfig=system("ifconfig");
  echo
$ifconfig;
 
$ifconfig=ob_get_contents();
 
ob_end_clean();
 
$ifconfig=explode(chr(10), $ifconfig);
  for (
$i=0; $i<count($ifconfig); $i++) {
   
$t=explode(" ", $ifconfig[$i]);
    if (
$t[0]=="\tinet") {
     
array_push($ips, $t[1]);
    }    
  }
  for (
$i=0; $i<count($ips); $i++) {
    echo
$ips[$i]."\n";
  }
?>

You will get list of IP adresses in $ips array, like:
82.146.XXX.XXX
78.24.XXX.XXX
82.146.XXX.XXX
82.146.XXX.XXX
82.146.XXX.XXX
78.24.XXX.XXX
78.24.XXX.XXX
Anonymous
01-Aug-2008 04:03
Be careful when following Salil Kothadia's suggestion of using http_build_query with CURLOPT_POSTFIELDS.

As pinkgothic at gmail dot com explains on the http_build_query page: "Be careful if you're assuming that arg_separator defaults to '&'." For example, XAMPP changes the default in PHP.ini to '& amp' which may cause hours of frustration when trying to resolve failed form submissions.
ac at an dot y-co dot de
11-Jul-2008 01:08
If you want to connect to a server which requires that you identify yourself with a certificate, use following code. Your certificate and servers certificate are signed by an authority whose certificate is in ca.ctr.

<?php
curl_setopt
($ch, CURLOPT_VERBOSE, '1');
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, '1');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, '1');
curl_setopt($ch, CURLOPT_CAINFOgetcwd().'/cert/ca.crt');
curl_setopt($ch, CURLOPT_SSLCERT, getcwd().'/cert/mycert.pem');
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, 'password');
?>

If your original certificate is in .pfx format, you have to convert it to .pem using following commands
# openssl pkcs12 -in mycert.pfx -out mycert.key
# openssl rsa -in mycert.key -out mycert.pem
# openssl x509 -in mycert.key >> mycert.pem
nick at glype dot com
08-Jul-2008 12:18
Although CURLOPT_CLOSEPOLICY and the applicable choices are valid constants, setting this option with curl_setopt() always returns false. A quick google search suggests the option is deprecated and/or never worked.
heron at xnapid dot com
20-Jun-2008 05:19
Someone posted this under tmpfile (http://us3.php.net/manual/en/function.tmpfile.php#69419), and I thought it was particularly useful:

By the way, this function is really useful for libcurl's CURLOPT_PUT feature if what you're trying to PUT is a string.   For example:

/* Create a cURL handle. */
$ch = curl_init();

/* Prepare the data for HTTP PUT. */
$putString = "Hello, world!";
$putData = tmpfile();
fwrite($putData, $putString);
fseek($putData, 0);

/* Set cURL options. */
curl_setopt($ch, CURLOPT_URL, "http://www.example.com");
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $putData);
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($putString));
/* ... (other curl options) ... */

/* Execute the PUT and clean up */
$result = curl_exec($ch);
fclose($putData);
curl_close($ch);
Salil Kothadia
20-Jun-2008 12:02
In PHP5, for the "CURLOPT_POSTFIELDS" option, we can use:

<?php
$ch
= curl_init($URI);
$Post = http_build_query($PostData);
curl_setopt($ch, CURLOPT_POSTFIELDS, $Post);
$Output = curl_exec($ch);
curl_close($ch);
?>
chaim1567 at googlemail dot com
09-Jun-2008 07:07
Be careful setting options while reusing a curl handle. I do not believe curl_exec resets the previous options e.g. the referrer and headers you set two requests ago may remain for the latest request.

I have not fully tested this and am interested in your results.
f00f
13-May-2008 03:17
Please note that the below is not entirely correct. This format will work partially, but does not always produce correct headers. The correct form for the same code is:
<?php
$str 
= array(
"Accept-Language: en-us,en;q=0.5",
"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7",
"Keep-Alive: 300",
"Connection: keep-alive"
);
      
curl_setopt($this->curl_handle, CURLOPT_HTTPHEADER, $str);
?>

The appropriate newlines/cr's *should* be handled by curl.

This realization has cost me many hours, because Host, User-Agent, Cache-Control, etc appear to be handled correctly with the string form, but Content-Length and Content-Type are duplicated and the second copy is not parsed correctly by the server!
hotrodder at rocketmail dot com
07-May-2008 09:26
I just spent the last 45 minutes banging my head against my keyboard because when using libcurl for a lighttpd server I would get a 400 Bad Request Error.

It turns out, that despite what has been mentioned in other comments, when using the CURLOPT_HTTPHEADER option, you must use \r\n as newline separators for each header NOT \n. For some reason lighttpd will not accept them. Other webservers will however.

Example:
<?php
$str 
= "Accept-Language: en-us,en;q=0.5\r\n";
$str .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
$str .= "Keep-Alive: 300\r\n";
$str .= "Connection: keep-alive\r\n";
       
curl_setopt($this->curl_handle, CURLOPT_HTTPHEADER, array($str));
?>
skylight at list ru
30-Apr-2008 05:31
OMG! I've joust found kinda bug:
YES, you can set an IP for curl to use by using this statement: curl_setopt($curl, CURLOPT_INTERFACE, $ip);
NO, you CAN NOT set another IP for the same curl object. I mean if u do curl_setopt($curl, CURLOPT_INTERFACE, $ip2); - it wont work!

So to change an IP you need to re-create curl object (curl_close, then curl_init).
sgamon at yahoo dot com
10-Apr-2008 08:55
If you are doing a POST, and the content length is 1,025 or greater, then curl exploits a feature of http 1.1: 100 (Continue) Status.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3

* it adds a header, "Expect: 100-continue". 
* it then sends the request head, waits for a 100 response code, then sends the content

Not all web servers support this though.  Various errors are returned depending on the server.  If this happens to you, suppress the "Expect" header with this command:

<?php
curl_setopt
($ch, CURLOPT_HTTPHEADER, array('Expect:'));
?>

See http://www.gnegg.ch/2007/02/the-return-of-except-100-continue/
john factorial
05-Apr-2008 12:22
Clarification for the CURLOPT_NOBODY option: by excluding the body from your request, you're effectively making a HEAD request. Use the CURLOPT_NOBODY option to return only the headers in the remote response.

Example:

function check_url($url) {
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, $url);
    curl_setopt($c, CURLOPT_HEADER, 1); // get the header
    curl_setopt($c, CURLOPT_NOBODY, 1); // and *only* get the header
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); // get the response as a string from curl_exec(), rather than echoing it
    curl_setopt($c, CURLOPT_FRESH_CONNECT, 1); // don't use a cached version of the url
    if (!curl_exec($c)) { return false; }

    $httpcode = curl_getinfo($c, CURLINFO_HTTP_CODE);
    return ($httpcode < 400);
}
mavook at gmail dot com
16-Feb-2008 02:26
If you try to upload file to a server, you need do CURLOPT_POST first and then fill CURLOPT_POSTFIELDS.
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
^^ This will post multipart/form-data

Next example don't work:
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
curl_setopt($ch, CURLOPT_POST, 1);
Sets to content-lenght:0 if $postvars an array.
meat_popsiclez at hotmail dot com
29-Dec-2007 01:13
Despite the documentation for CURLOPT_HTTPHEADER, all header fields MUST be in one string, with a eol indicator, inside a single element array, in my experience.

For example, this will fail.
<?php
curl_setopt
($ch, CURLOPT_HTTPHEADER, array("Range: Bytes=0-50"));
?>

This will work.
<?php
curl_setopt
($ch, CURLOPT_HTTPHEADER, array("Range: Bytes=0-50\n"));
?>

This will only set the first header
<?php
curl_setopt
($ch, CURLOPT_HTTPHEADER, array("Range: Bytes=0-50\n","Otherheader: stuff\n"));
?>

This however, will set both headers as we want.
<?php
curl_setopt
($ch, CURLOPT_HTTPHEADER, array("Range: Bytes=0-50\nOtherheader: stuff\n"));
?>
contacto at hardcode dot com dot ar
13-Dec-2007 04:34
hey hey hey!
the problem: curl_setopt($ch,FOLLOW_LOCATION,1);
the error: trouble with open_basedir and safe_mode
the solution: a function already developed by someone
the solution n 2: the same function, modifed, works great for me..

function curl_redir_exec($ch,$debug="")
{
    static $curl_loops = 0;
    static $curl_max_loops = 20;

    if ($curl_loops++ >= $curl_max_loops)
    {
        $curl_loops = 0;
        return FALSE;
    }
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    $debbbb = $data;
    list($header, $data) = explode("\n\n", $data, 2);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($http_code == 301 || $http_code == 302) {
        $matches = array();
        preg_match('/Location:(.*?)\n/', $header, $matches);
        $url = @parse_url(trim(array_pop($matches)));
        //print_r($url);
        if (!$url)
        {
            //couldn't process the url to redirect to
            $curl_loops = 0;
            return $data;
        }
        $last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
    /*    if (!$url['scheme'])
            $url['scheme'] = $last_url['scheme'];
        if (!$url['host'])
            $url['host'] = $last_url['host'];
        if (!$url['path'])
            $url['path'] = $last_url['path'];*/
        $new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
        curl_setopt($ch, CURLOPT_URL, $new_url);
    //    debug('Redirecting to', $new_url);

        return curl_redir_exec($ch);
    } else {
        $curl_loops=0;
        return $debbbb;
    }
}

just use this function without de FOLLOW_LOCATION and should work. the problem was that when you get to the line where you return the data if http_code was different than 301 oe 302, $data has obsolete information or none. so $debbbb does the job.

hope this helps someone out there

thanks from argentina
andrabr at gmail dot com
21-Aug-2007 05:03
This is very clear in hindsight, but it still cost me several hours:

 curl_setopt($session, CURLOPT_HTTPPROXYTUNNEL, 1);

means that you will tunnel THROUGH the proxy, as in "your communications will go as if the proxy is NOT THERE".

Why do you care? - Well, if you are trying to use, say, Paros, to debug HTTP between your cURL and the server, with CURLOPT_HTTPPROXYTUNNEL set to TRUE Paros will not see or log your traffic thus defeating the purpose and driving you nuts.

There are other cases, of course, where this option is extremely useful...
chuck
21-Jul-2007 12:07
The explanation of CURLOPT_NOBODY ("TRUE to exclude the body from the output.") seems unclear to me -- I originally read "output" to mean the return value, i.e. the response.  In fact it means to exclude the body from your *request*.  Not sure whether "output" means the same thing for CURLOPT_HEADER though.
michael sky
06-Jul-2007 06:09
if you are trying to connect to 'https://...' and after that want to work with POST data - that's the way:

$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_COOKIEFILE, "cookiefile");
curl_setopt($curl, CURLOPT_COOKIEJAR, "cookiefile"); # SAME cookiefile
curl_setopt($curl, CURLOPT_URL, "url1"); # this is where you first time connect - GET method authorization in my case, if you have POST - need to edit code a bit
$xxx = curl_exec($curl);

curl_setopt($curl, CURLOPT_URL, "url2"); # this is where you are requesting POST-method form results (working with secure connection using cookies after auth)
curl_setopt($curl, CURLOPT_POSTFIELDS, "var1=value&var2=value&var3=value&"); # form params that'll be used to get form results
$xxx = curl_exec($curl);

curl_close ($curl);
echo $xxx;
sleepwalker at rahulsjohari dot com
28-Jun-2007 02:18
Two things that I noted, one of which has been mentioned earlier, if you are connecting to an SSL site (https) and don't have the appropriate certificate, don't forget to set CURLOPT_SSL_VERIFYPEER as "false"... it's set to "true" by default. Scratched my head over 2 hours to figure this one out as I had a machine with an older version installed and everything worked fine without using this option on that one - but failed on other machines with newer versions.

Second very important thing, I've never had my scripts work (tried on various machines, multiple platforms) with a Relative path to a COOKIEJAR or COOKIEFILE. In my experience I HAVE to specify the absolute path and not the relative path.

Small script I wrote to connect to a page, gather all cookies into a jar, connect to another page to login, taking the cookiejar with you for authentication:

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/Library/WebServer/Documents/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"https://www.example.com/myaccount/start.asp");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
ob_start();      // Prevent output
curl_exec ($ch);
ob_end_clean();  // End preventing output
curl_close ($ch);
unset($ch);

$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "field1=".$f1."&field2=".$f2."&SomeFlag=True");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/Library/WebServer/Documents/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"https://www.example.com/myaccount/Login.asp");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec ($ch);
curl_close ($ch);
mcbreen at gmail dot com
13-Jun-2007 05:35
If you are getting the following error:

SSL: certificate subject name 'domain-or-ip-1.com' does not match target host name 'domain-or-ip-2.com'

Then you can set the following option to get around it:

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
vincent at ludden dot nl
12-Jun-2007 04:55
Please note that the CURLOPT_INTERFACE setting only accepts IP addresses and hostnames of the local machine. It is not meant to send a URL to a specific IP address.
Jon Freilich
12-May-2007 12:52
curl will sometimes return an "Empty reply from server" error if you don't send a User-Agent string.  Use the CURLOPT_USERAGENT option.
rob at infoglobe dot net
25-Apr-2007 12:01
Options not included in the above, but that work (Taken from the libcurl.a C documentation)

CURLOPT_FTP_SSL

Pass a long using one of the values from below, to make libcurl use your desired level of SSL for the ftp transfer. (Added in 7.11.0)

CURLFTPSSL_NONE

Don't attempt to use SSL.

CURLFTPSSL_TRY

Try using SSL, proceed as normal otherwise.

CURLFTPSSL_CONTROL

Require SSL for the control connection or fail with CURLE_FTP_SSL_FAILED.

CURLFTPSSL_ALL

Require SSL for all communication or fail with CURLE_FTP_SSL_FAILED.
alfredoaguirre dot v at gmail dot com
14-Mar-2007 08:26
Seems that CURLOPT_RETURNTRANSFER Option set to TRUE, returns a "1" when the transaction returns a blank page.

I think is for eliminate the FALSE to can be with a blank page as return
paczor
08-Mar-2007 10:50
How to get rid of response after POST: just add callback function for returned data (CURLOPT_WRITEFUNCTION) and make this function empty.

function curlHeaderCallback($ch, $strHeader) {
}
curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'curlHeaderCallback')
Killerwhile
03-Mar-2007 10:36
In response to "brett at brettbrewer dot com" and Jamolkhon, the fact you don't take into account is when a redirection (Location: ...) occurs, all the headers are given so the \r\n\r\n can also separate twp consecutive headers.

An even better trick to get the header is to use CURLINFO_HEADER_SIZE :

$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

$headers = substr($output, 0, $header_size - 4);
$body = substr($output, $header_size);

Then $headers contains all the headers.
Jamolkhon
16-Dec-2006 03:11
in response to "brett at brettbrewer dot com":
another useful way of getting headers without using regular expression

<?php

class CCurl {
    var
$m_handle;
    var
$m_header;
    var
$m_body;
   
    function
CCurl($sUrl) {
       
$this->m_handle = curl_init();
       
curl_setopt($this->m_handle, CURLOPT_URL, $sUrl);
       
curl_setopt($this->m_handle, CURLOPT_HEADER, 1);
       
curl_setopt($this->m_handle, CURLOPT_RETURNTRANSFER, 1);
        return;
    }
   
    function
getHeader() {
        return
$this->m_header;
    }
   
    function
execute() {
       
$sResponse = curl_exec($this->m_handle);
       
$this->m_body = substr($sResponse, strpos($sResponse, "\r\n\r\n") + 4);
       
$this->m_header = substr($sResponse, 0, -strlen($this->m_body));
        return
$this->m_body;
    }
   
    function
close() {
       
curl_close($this->m_handle);
        return;
    }
}

?>

(you can add something or make some changes to suit your needs)
eion at bigfoot dot com
22-Nov-2006 12:40
If you are trying to use CURLOPT_FOLLOWLOCATION and you get this warning:
Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set...

then you will want to read http://www.php.net/ChangeLog-4.php which says "Disabled CURLOPT_FOLLOWLOCATION in curl when open_basedir or safe_mode are enabled." as of PHP 4.4.4/5.1.5.  This is due to the fact that curl is not part of PHP and doesn't know the values of open_basedir or safe_mode, so you could comprimise your webserver operating in safe_mode by redirecting (using header('Location: ...')) to "file://" urls, which curl would have gladly retrieved.

Until the curl extension is changed in PHP or curl (if it ever will) to deal with "Location:" headers, here is a far from perfect remake of the curl_exec function that I am using.

Since there's no curl_getopt function equivalent, you'll have to tweak the function to make it work for your specific use.  As it is here, it returns the body of the response and not the header.  It also doesn't deal with redirection urls with username and passwords in them.

<?php
   
function curl_redir_exec($ch)
    {
        static
$curl_loops = 0;
        static
$curl_max_loops = 20;
        if (
$curl_loops++ >= $curl_max_loops)
        {
           
$curl_loops = 0;
            return
FALSE;
        }
       
curl_setopt($ch, CURLOPT_HEADER, true);
       
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       
$data = curl_exec($ch);
        list(
$header, $data) = explode("\n\n", $data, 2);
       
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if (
$http_code == 301 || $http_code == 302)
        {
           
$matches = array();
           
preg_match('/Location:(.*?)\n/', $header, $matches);
           
$url = @parse_url(trim(array_pop($matches)));
            if (!
$url)
            {
               
//couldn't process the url to redirect to
               
$curl_loops = 0;
                return
$data;
            }
           
$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
            if (!
$url['scheme'])
               
$url['scheme'] = $last_url['scheme'];
            if (!
$url['host'])
               
$url['host'] = $last_url['host'];
            if (!
$url['path'])
               
$url['path'] = $last_url['path'];
           
$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
           
curl_setopt($ch, CURLOPT_URL, $new_url);
           
debug('Redirecting to', $new_url);
            return
curl_redir_exec($ch);
        } else {
           
$curl_loops=0;
            return
$data;
        }
    }
?>
jochem AT hotmail dot com
10-Nov-2006 03:27
I have seen two posts complaining the "CURLOPT_POSTFIELDS" option is not working well.

This was the solution given below:

   $o="";
   foreach ($post_data as $k=>$v)
   {
       $o.= "$k=".utf8_encode($v)."&";
   }
   $post_data=substr($o,0,-1);

The assumption that this is an error is not true, as stated on http://curl.rtin.bz/docs/httpscripting.html:
"  The data you send to the server MUST already be properly encoded, curl will
  not do that for you. For example, if you want the data to contain a space,
  you need to replace that space with %20 etc. Failing to comply with this
  will most likely cause your data to be received wrongly and messed up."

This means you do really have to encode the data yourself the right way.
zarko at svetlozar dot net
01-Oct-2006 07:51
As Yevgen mentioned earlier sometimes we can't use CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE. Below is a header callback function I wrote back in January that lets you maintain cookies between cURL requests. Cookies are added to $ch during all requests even during redirection, so you can use it together with CURLOPT_FOLLOWLOCATION.
Here is the code:

function read_header($ch, $string)
{
    global $location; #keep track of location/redirects
    global $cookiearr; #store cookies here
    global $ch;
       # ^overrides the function param $ch
       # this is okay because we need to
       # update the global $ch with
       # new cookies
   
    $length = strlen($string);
    if(!strncmp($string, "Location:", 9))
    { #keep track of last redirect
      $location = trim(substr($string, 9, -1));
    }
    if(!strncmp($string, "Set-Cookie:", 11))
    { #get the cookie
      $cookiestr = trim(substr($string, 11, -1));
      $cookie = explode(';', $cookiestr);
      $cookie = explode('=', $cookie[0]);
      $cookiename = trim(array_shift($cookie));
      $cookiearr[$cookiename] = trim(implode('=', $cookie));
    }
    $cookie = "";
    if(trim($string) == "")
    {  #execute only at end of header
      foreach ($cookiearr as $key=>$value)
      {
        $cookie .= "$key=$value; ";
      }
      curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }

    return $length;
}

Using the header function with curl (add this before curl_exec):

#don't forget globals, especially if you are using this in function
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');

This code assumes that you will reuse $ch without initializing it every time (call curl_init only once, in the beginning). If you need to initialize $ch again at any point in your code you can access the currently stored cookies in $cookiearr and include them in the new $ch.

I wrote this function before I had enough experience with regular expressions so you won't find any preg_match calls here. I have used this code for quite a while and without any problems accessing gmail, yahoo, hotmail, aol etc. where I had to go through login and a few pages before getting to what I was looking for.

Svetlozar Petrov (http://svetlozar.net)
php at miggy dot org
24-Aug-2006 01:35
Note that if you want to use a proxy and use it as a _cache_, you'll have to do:

curl_setopt($ch, CURLOPT_HTTPHEADER, array("Pragma: "));

else by default Curl puts a "Pragma: no-cache" header in and thus force cache misses for all requests.
bendavis78 at gmail dot com
14-Jul-2006 06:58
You can use CURLOPT_HEADERFUNCTION  with a callback inside an object.  This makes is it easy to capture the headers for later use.  For example:
<?
class Test
{
    public $headers;

    //...

    public function exec($opts)
 &n