For some reason I am unable to use CURL with HTTPS. Everything was working fine untill I ran upgrade of curl libraries. Now I am experiencing this response when trying to perform CURL requests: Problem with the SSL CA cert (path? access rights?)
Following suggestions posted here on related issues I have tried to do the following:
-
Disable verification for host and peer
curl_setopt($cHandler, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($cHandler, CURLOPT_SSL_VERIFYPEER, true);
-
Enable
CURLOPT_SSL_VERIFYPEER
and point to cacert.pem downloaded from http://curl.haxx.se/docs/caextract.htmlcurl_setopt($cHandler, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($cHandler, CURLOPT_CAINFO, getcwd() . "/positiveSSL.ca-bundle");
-
I also tried to do the same thing with positiveSSL.ca-bundle which was provided as bundle CA certificate for the server I am trying to connect to.
-
Edit php ini settings with
curl.cainfo=cacert.pem
(file in the same directory and accessible by apache) -
Rename
/etc/pki/nssdb
to/etc/pki/nssdb.old
Unfortunatelly none of the above are able to solve my problem and I constantly get Problem with the SSL CA cert (path? access rights?) message.
And I don’t need this verification in the first place (I am aware of security issues).
Does anybody have any other suggestions?
UPDATE
After updating to the latest libraries and restart of the whole box, not just apache which I was doing it all seems to be working now again!!!
gustavohenke
40.8k14 gold badges120 silver badges127 bronze badges
asked Feb 28, 2013 at 12:41
6
According to documentation: to verify host or peer certificate you need to specify alternate certificates with the CURLOPT_CAINFO
option or a certificate directory can be specified with the CURLOPT_CAPATH
option.
Also look at 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.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
answered Mar 6, 2013 at 1:10
cloverclover
4,8301 gold badge18 silver badges26 bronze badges
3
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return data inplace of echoing on screen
curl_setopt($ch, CURLOPT_URL, $strURL);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // Skip SSL Verification
$rsData = curl_exec($ch);
curl_close($ch);
return $rsData;
answered Feb 23, 2022 at 4:01
We had the same problem on a CentOS7 machine. Disabling the VERIFYHOST
VERIFYPEER
did not solve the problem, we did not have the cURL error anymore but the response still was invalid. Doing a wget
to the same link as the cURL was doing also resulted in a certificate error.
-> Our solution also was to reboot the VPS, this solved it and we were able to complete the request again.
For us this seemed to be a memory corruption problem. Rebooting the VPS reloaded the libary in the memory again and now it works. So if the above solution from @clover
does not work try to reboot your machine.
answered Jun 8, 2016 at 10:54
RvanlaakRvanlaak
2,96120 silver badges39 bronze badges
1
Try below if working for you:
For SSL verification we need to set 2
CURLOPT_SSL_VERIFYHOST =2
CURLOPT_SSL_VERIFYPEER =2
For not verification we need to set 0
CURLOPT_SSL_VERIFYHOST =0
CURLOPT_SSL_VERIFYPEER =0
default is always false
answered May 19 at 5:58
1
Ignore SSL Certificate errors in PHP (good for debugging or when connecting to trusted domains that re using Let’s Encrypt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $url); | |
curl_setopt($ch, CURLOPT_POST, 1); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data) ); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
// Ignore SSL Certificate errors | |
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); | |
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); | |
$html = curl_exec($ch); | |
if (curl_errno($ch)) { | |
$html = ‘ERROR: ‘ . curl_error($ch); | |
} | |
curl_close ($ch); | |
?> |
In this article, I will show share with you a tip to fix SSL certificate problem with PHP curl when making HTTPS requests.
Making HTTPS requests
Before talking about the issue, let us try an old example by making HTTP request.
$url = "http://WEBSITE";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if(curl_errno($ch)) {
echo 'Error: '.curl_error($ch);
} else {
echo $result;
}
curl_close ($ch);
It is alright for HTTP site, but if we change the $url
into a HTTPS url, ex. https://petehouston.com
, does it work normally?
No, it doesn’t. It shows this nagging error:
Error: SSL certificate problem: unable to get local issuer certificate
The error means we need to configure curl instance to deal with SSL-enabled websites.
Fix SSL certificate problem
There are two ways to fix SSL certificate problem with PHP curl module.
- Specify the valid CA certificate to curl client.
- Ignore SSL verification.
Solution 1: Use a valid CA certificate
I’m not going to explain what CA certificate is and why we need it to make requests.
You just need to download CA certificate provided by curl author, https://curl.haxx.se/docs/caextract.html, or click here to download.
Save the file somewhere in your computer, ex. ~/certs/cacert.pem
if you’re on Linux or MacOS, D:certscacert.pem
if you’re using Windows.
Config the curl instance with CURLOPT_CAINFO
to point to the cacert.pem
file.
// for Linux/Mac
curl_setopt($ch, CURLOPT_CAINFO, '/home/petehouston/certs/cacert.pem');
// for Windows
curl_setopt($ch, CURLOPT_CAINFO, 'D:/certs/cacert.pem');
Try to execute the script again, it should work now!
You can also pre-configure the CA certificate by putting it into php.ini
, so you don’t need to configure manually for each curl instance.
[curl]
; A default value for the CURLOPT_CAINFO option. This is required to be an
; absolute path.
curl.cainfo = "/home/petehouston/certs/cacert.pem"
Solution 2: Ignore SSL verification
If you don’t really care about SSL verification, you can ignore it by disable the CURLOPT_SSL_VERIFYPEER
key.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
It is just working as it with configured certificate.
Conclusion
So which one should I use, you ask?
Again, if you don’t care about the authenticity of the SSL then ignore it; otherwise, make sure you request to the right one.
That’s it! I’ve just shown you how to fix SSL certificate problem with PHP curl module.
up vote 0
down vote
Нужно отключить проверку валидности ssl сертификата:
отключить curl SSL опции CURLOPT_SSL_VERIFYPEER, CURLOPT_SSL_VERIFYHOST в ваш curl-клиенте:
$client->setOption(CURLOPT_SSL_VERIFYPEER, false);
$client->setOption(CURLOPT_SSL_VERIFYHOST, false);
$client->setOption(CURLOPT_SSLVERSION, 3);
На «чистом» curl отключение проверки ssl-сертификата выглядит так:
$ch = curl_init($url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
ответил 9 лет назад
root |
(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP
curl_setopt — Set an option for a cURL transfer
Description
curl_setopt(CurlHandle $handle
, int $option
, mixed $value
): bool
Parameters
-
handle
-
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 theoption
parameter:Option Set value
toNotes CURLOPT_AUTOREFERER
true
to automatically set theReferer:
field in
requests where it follows aLocation:
redirect.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 or not.
Session cookies are cookies without expiry date and they are meant
to be alive and existing for this «session» only.CURLOPT_CERTINFO
true
to output SSL certification information toSTDERR
on secure transfers.Added in cURL 7.19.1.
RequiresCURLOPT_VERBOSE
to be on to have an effect.CURLOPT_CONNECT_ONLY
true
tells the library to perform all the required proxy authentication
and connection setup, but no data transfer. This option is implemented for
HTTP, SMTP and POP3.Added in 7.15.2. CURLOPT_CRLF
true
to convert Unix newlines to CRLF newlines
on transfers.CURLOPT_DISALLOW_USERNAME_IN_URL
true
to not allow URLs that include a username. Usernames are allowed by default (0).Added in cURL 7.61.0. Available since PHP 7.3.0. CURLOPT_DNS_SHUFFLE_ADDRESSES
true
to shuffle the order of all returned addresses so that they will be used
in a random order, when a name is resolved and more than one IP address is returned.
This may cause IPv4 to be used before IPv6 or vice versa.Added in cURL 7.60.0. Available since PHP 7.3.0. CURLOPT_HAPROXYPROTOCOL
true
to send an HAProxy PROXY protocol v1 header at the start of the connection.
The default action is not to send this header.Added in cURL 7.60.0. Available since PHP 7.3.0. CURLOPT_SSH_COMPRESSION
true
to enable built-in SSH compression. This is a request, not an order;
the server may or may not do it.Added in cURL 7.56.0. Available since PHP 7.3.0. CURLOPT_DNS_USE_GLOBAL_CACHE
true
to use a global DNS cache. This option is not thread-safe.
It is conditionally enabled by default if PHP is built for non-threaded use
(CLI, FCGI, Apache2-Prefork, etc.).CURLOPT_FAILONERROR
true
to fail verbosely 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_SSL_FALSESTART
true
to enable TLS false start.Added in cURL 7.42.0. Available since PHP 7.0.7. CURLOPT_FILETIME
true
to attempt to retrieve the modification
date of the remote document. This value can be retrieved using
theCURLINFO_FILETIME
option with
curl_getinfo().CURLOPT_FOLLOWLOCATION
true
to follow any
"Location: "
header that the server sends as
part of the HTTP header.
See alsoCURLOPT_MAXREDIRS
.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. Usefalse
to disable EPRT and LPRT and use PORT
only.CURLOPT_FTP_USE_EPSV
true
to first try an EPSV command for FTP
transfers before reverting back to PASV. Set tofalse
to disable EPSV.CURLOPT_FTP_CREATE_MISSING_DIRS
true
to create missing directories when an FTP operation
encounters a path that currently doesn’t exist.CURLOPT_FTPAPPEND
true
to append to the remote file instead of
overwriting it.CURLOPT_TCP_NODELAY
true
to disable TCP’s Nagle algorithm, which tries to minimize
the number of small packets on the network.Available for versions compiled with libcurl 7.11.2 or
greater.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.CURLINFO_HEADER_OUT
true
to track the handle’s request string.The CURLINFO_
prefix is intentional.CURLOPT_HTTP09_ALLOWED
Whether to allow HTTP/0.9 responses. Defaults to false
as of libcurl 7.66.0;
formerly it defaulted totrue
.Available since PHP 7.3.15 and 7.4.3, respectively, if built against libcurl >= 7.64.0 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_HTTP_CONTENT_DECODING
false
to get the raw HTTP response body.Available if built against libcurl >= 7.16.2. CURLOPT_KEEP_SENDING_ON_ERROR
true
to keep sending the request body if the HTTP code returned is
equal to or larger than 300. The default action would be to stop sending
and close the stream or connection. Suitable for manual NTLM authentication.
Most applications do not need this option.Available as of PHP 7.3.0 if built against libcurl >= 7.51.0. CURLOPT_MUTE
true
to be completely silent with regards to
the cURL functions.Removed in cURL 7.15.5 (You can use CURLOPT_RETURNTRANSFER instead) 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.
Request method is then set to HEAD. Changing this tofalse
does
not change it to GET.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. CURLOPT_PATH_AS_IS
true
to not handle dot dot sequences.Added in cURL 7.42.0. Available since PHP 7.0.7. CURLOPT_PIPEWAIT
true
to wait for pipelining/multiplexing.Added in cURL 7.43.0. Available since PHP 7.0.7. CURLOPT_POST
true
to do a regular HTTP POST. This POST is the
normalapplication/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 withCURLOPT_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 directly.CURLOPT_SASL_IR
true
to enable sending the initial response in the first packet.Added in cURL 7.31.10. Available since PHP 7.0.7. CURLOPT_SSL_ENABLE_ALPN
false
to disable ALPN in the SSL handshake (if the SSL backend
libcurl is built to use supports it), which can be used to
negotiate http2.Added in cURL 7.36.0. Available since PHP 7.0.7. CURLOPT_SSL_ENABLE_NPN
false
to disable NPN in the SSL handshake (if the SSL backend
libcurl is built to use supports it), which can be used to
negotiate http2.Added in cURL 7.36.0. Available since PHP 7.0.7. CURLOPT_SSL_VERIFYPEER
false
to stop cURL from verifying the peer’s
certificate. Alternate certificates to verify against can be
specified with theCURLOPT_CAINFO
option
or a certificate directory can be specified with the
CURLOPT_CAPATH
option.true
by default as of cURL 7.10. Default bundle installed as of
cURL 7.10.CURLOPT_SSL_VERIFYSTATUS
true
to verify the certificate’s status.Added in cURL 7.41.0. Available since PHP 7.0.7. CURLOPT_PROXY_SSL_VERIFYPEER
false
to stop cURL from verifying the peer’s certificate.
Alternate certificates to verify against can be
specified with theCURLOPT_CAINFO
option
or a certificate directory can be specified with the
CURLOPT_CAPATH
option.
When set to false, the peer certificate verification succeeds regardless.true
by default. Available since PHP 7.3.0 and libcurl >= cURL 7.52.0.CURLOPT_SAFE_UPLOAD
Always true
, what disables support for the@
prefix for
uploading files inCURLOPT_POSTFIELDS
, which
means that values starting with@
can be safely
passed as fields. CURLFile may be used for
uploads instead.CURLOPT_SUPPRESS_CONNECT_HEADERS
true
to suppress proxy CONNECT response headers from the user callback functions
CURLOPT_HEADERFUNCTION
andCURLOPT_WRITEFUNCTION
,
whenCURLOPT_HTTPPROXYTUNNEL
is used and a CONNECT request is made.Added in cURL 7.54.0. Available since PHP 7.3.0. CURLOPT_TCP_FASTOPEN
true
to enable TCP Fast Open.Added in cURL 7.49.0. Available since PHP 7.0.7. CURLOPT_TFTP_NO_OPTIONS
true
to not send TFTP options requests.Added in cURL 7.48.0. Available since PHP 7.0.7. 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 setSTDOUT
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.CURLOPT_UPLOAD
true
to prepare for an upload.CURLOPT_VERBOSE
true
to output verbose information. Writes
output toSTDERR
, or the file specified using
CURLOPT_STDERR
.value
should be an int for the
following values of theoption
parameter:Option Set value
toNotes 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. CURLOPT_CONNECTTIMEOUT
The number of seconds to wait while trying to connect. Use 0 to
wait indefinitely.CURLOPT_CONNECTTIMEOUT_MS
The number of milliseconds to wait while trying to connect. Use 0 to
wait indefinitely.If libcurl is built to use the standard system name resolver, that
portion of the connect will still use full-second resolution for
timeouts with a minimum timeout allowed of one second.Added in cURL 7.16.2. 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_EXPECT_100_TIMEOUT_MS
The timeout for Expect: 100-continue responses in milliseconds.
Defaults to 1000 milliseconds.Added in cURL 7.36.0. Available since PHP 7.0.7. CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS
Head start for ipv6 for the happy eyeballs algorithm. Happy eyeballs attempts
to connect to both IPv4 and IPv6 addresses for dual-stack hosts,
preferring IPv6 first for timeout milliseconds.
Defaults to CURL_HET_DEFAULT, which is currently 200 milliseconds.Added in cURL 7.59.0. Available since PHP 7.3.0. 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. CURLOPT_HEADEROPT
How to deal with headers. One of the following constants:
CURLHEADER_UNIFIED
: the headers specified in
CURLOPT_HTTPHEADER
will be used in requests
both to servers and proxies. With this option enabled,
CURLOPT_PROXYHEADER
will not have any effect.
CURLHEADER_SEPARATE
: makes
CURLOPT_HTTPHEADER
headers only get sent to
a server and not to a proxy. Proxy headers must be set with
CURLOPT_PROXYHEADER
to get used. Note that if
a non-CONNECT request is sent to a proxy, libcurl will send both
server headers and proxy headers. When doing CONNECT, libcurl will
sendCURLOPT_PROXYHEADER
headers only to the
proxy and thenCURLOPT_HTTPHEADER
headers
only to the server.
Defaults toCURLHEADER_SEPARATE
as of cURL
7.42.1, andCURLHEADER_UNIFIED
before.
Added in cURL 7.37.0. Available since PHP 7.0.7. CURLOPT_HTTP_VERSION
CURL_HTTP_VERSION_NONE
(default, lets CURL
decide which version to use),
CURL_HTTP_VERSION_1_0
(forces HTTP/1.0),
CURL_HTTP_VERSION_1_1
(forces HTTP/1.1),
CURL_HTTP_VERSION_2_0
(attempts HTTP 2),
CURL_HTTP_VERSION_2
(alias ofCURL_HTTP_VERSION_2_0
),
CURL_HTTP_VERSION_2TLS
(attempts HTTP 2 over TLS (HTTPS) only) or
CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE
(issues non-TLS HTTP requests using HTTP/2 without HTTP/1.1 Upgrade).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
.CURLOPT_INFILESIZE
The expected size, in bytes, of the file when uploading a file to
a remote site. Note that using this option will not stop libcurl
from sending more data, as exactly what is sent depends on
CURLOPT_READFUNCTION
.CURLOPT_LOW_SPEED_LIMIT
The transfer speed, in bytes per second, that the transfer should be
below during the count ofCURLOPT_LOW_SPEED_TIME
seconds before PHP considers the transfer too slow and aborts.CURLOPT_LOW_SPEED_TIME
The number of seconds the transfer speed should be below
CURLOPT_LOW_SPEED_LIMIT
before PHP considers
the transfer too slow and aborts.CURLOPT_MAXCONNECTS
The maximum amount of persistent connections that are allowed.
When the limit is reached, the oldest one in the cache is closed
to prevent increasing the number of open connections.CURLOPT_MAXREDIRS
The maximum amount of HTTP redirections to follow. Use this option
alongsideCURLOPT_FOLLOWLOCATION
.
Default value of20
is set to prevent infinite redirects.
Setting to-1
allows inifinite redirects, and0
refuses all redirects.CURLOPT_PORT
An alternative port number to connect to. CURLOPT_POSTREDIR
A bitmask of 1 (301 Moved Permanently), 2 (302 Found)
and 4 (303 See Other) if the HTTP POST method should be maintained
whenCURLOPT_FOLLOWLOCATION
is set and a
specific type of redirect occurs.Added in cURL 7.19.1. CURLOPT_PROTOCOLS
Bitmask of
CURLPROTO_*
values. If used, this bitmask
limits what protocols libcurl may use in the transfer. This allows you to have
a libcurl built to support a wide range of protocols but still limit specific
transfers to only be allowed to use a subset of them. By default libcurl will
accept all protocols it supports.
See alsoCURLOPT_REDIR_PROTOCOLS
.Valid 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 authentication method(s) to use for the proxy connection.
Use the same bitmasks as described in
CURLOPT_HTTPAUTH
. For proxy authentication,
onlyCURLAUTH_BASIC
and
CURLAUTH_NTLM
are currently supported.Added in cURL 7.10.7. CURLOPT_PROXYPORT
The port number of the proxy to connect to. This port number can
also be set inCURLOPT_PROXY
.CURLOPT_PROXYTYPE
Either CURLPROXY_HTTP
(default),
CURLPROXY_SOCKS4
,
CURLPROXY_SOCKS5
,
CURLPROXY_SOCKS4A
or
CURLPROXY_SOCKS5_HOSTNAME
.Added in cURL 7.10. CURLOPT_REDIR_PROTOCOLS
Bitmask of CURLPROTO_*
values. If used, this bitmask
limits what protocols libcurl may use in a transfer that it follows to in
a redirect whenCURLOPT_FOLLOWLOCATION
is enabled.
This allows you to limit specific transfers to only be allowed to use a subset
of protocols in redirections. By default libcurl will allow all protocols
except for FILE and SCP. This is a difference compared to pre-7.19.4 versions
which unconditionally would follow to all protocols supported.
See alsoCURLOPT_PROTOCOLS
for protocol constant values.Added in cURL 7.19.4. CURLOPT_RESUME_FROM
The offset, in bytes, to resume a transfer from. CURLOPT_SOCKS5_AUTH
The SOCKS5 authentication method(s) to use. The options are:
CURLAUTH_BASIC
,
CURLAUTH_GSSAPI
,
CURLAUTH_NONE
.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_BASIC
allows username/password authentication.CURLAUTH_GSSAPI
allows GSS-API authentication.CURLAUTH_NONE
allows no authentication.Defaults to
CURLAUTH_BASIC|CURLAUTH_GSSAPI
.
Set the actual username and password with theCURLOPT_PROXYUSERPWD
option.Available as of 7.3.0 and curl >= 7.55.0. CURLOPT_SSL_OPTIONS
Set SSL behavior options, which is a bitmask of any of the following constants:
CURLSSLOPT_ALLOW_BEAST
: do not attempt to use
any workarounds for a security flaw in the SSL3 and TLS1.0 protocols.
CURLSSLOPT_NO_REVOKE
: disable certificate
revocation checks for those SSL backends where such behavior is
present.
Added in cURL 7.25.0. Available since PHP 7.0.7. CURLOPT_SSL_VERIFYHOST
2
to verify that a Common Name field or a Subject Alternate Name
field in the SSL peer certificate matches the provided hostname.
0
to not check the names.
1
should not be used.
In production environments the value of this option
should be kept at2
(default value).Support for value 1
removed in cURL 7.28.1.CURLOPT_SSLVERSION
One of CURL_SSLVERSION_DEFAULT
(0),
CURL_SSLVERSION_TLSv1
(1),
CURL_SSLVERSION_SSLv2
(2),
CURL_SSLVERSION_SSLv3
(3),
CURL_SSLVERSION_TLSv1_0
(4),
CURL_SSLVERSION_TLSv1_1
(5),
CURL_SSLVERSION_TLSv1_2
(6) or
CURL_SSLVERSION_TLSv1_3
(7).
The maximum TLS version can be set by using one of theCURL_SSLVERSION_MAX_*
constants. It is also possible to OR one of theCURL_SSLVERSION_*
constants with one of theCURL_SSLVERSION_MAX_*
constants.
CURL_SSLVERSION_MAX_DEFAULT
(the maximum version supported by the library),
CURL_SSLVERSION_MAX_TLSv1_0
,
CURL_SSLVERSION_MAX_TLSv1_1
,
CURL_SSLVERSION_MAX_TLSv1_2
, or
CURL_SSLVERSION_MAX_TLSv1_3
.Note:
Your best bet is to not set this and let it use the default.
Setting it to 2 or 3 is very dangerous given the known
vulnerabilities in SSLv2 and SSLv3.CURLOPT_PROXY_SSL_OPTIONS
Set proxy SSL behavior options, which is a bitmask of any of the following constants:
CURLSSLOPT_ALLOW_BEAST
: do not attempt to use
any workarounds for a security flaw in the SSL3 and TLS1.0 protocols.
CURLSSLOPT_NO_REVOKE
: disable certificate
revocation checks for those SSL backends where such behavior is
present. (curl >= 7.44.0)
CURLSSLOPT_NO_PARTIALCHAIN
: do not accept «partial»
certificate chains, which it otherwise does by default. (curl >= 7.68.0)
Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. CURLOPT_PROXY_SSL_VERIFYHOST
Set to 2
to verify in the HTTPS proxy’s certificate name fields against the proxy name.
When set to0
the connection succeeds regardless of the names used in the certificate.
Use that ability with caution!
1
treated as a debug option in curl 7.28.0 and earlier.
From curl 7.28.1 to 7.65.3CURLE_BAD_FUNCTION_ARGUMENT
is returned.
From curl 7.66.0 onwards1
and2
is treated as the same value.
In production environments the value of this option should be kept at2
(default value).Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. CURLOPT_PROXY_SSLVERSION
One of CURL_SSLVERSION_DEFAULT
,
CURL_SSLVERSION_TLSv1
,
CURL_SSLVERSION_TLSv1_0
,
CURL_SSLVERSION_TLSv1_1
,
CURL_SSLVERSION_TLSv1_2
,
CURL_SSLVERSION_TLSv1_3
,
CURL_SSLVERSION_MAX_DEFAULT
,
CURL_SSLVERSION_MAX_TLSv1_0
,
CURL_SSLVERSION_MAX_TLSv1_1
,
CURL_SSLVERSION_MAX_TLSv1_2
,
CURL_SSLVERSION_MAX_TLSv1_3
or
CURL_SSLVERSION_SSLv3
.Note:
Your best bet is to not set this and let it use the default
CURL_SSLVERSION_DEFAULT
which will attempt to figure out the remote SSL protocol version.Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. CURLOPT_STREAM_WEIGHT
Set the numerical stream weight (a number between 1 and 256). Added in cURL 7.46.0. Available since PHP 7.0.7. CURLOPT_TCP_KEEPALIVE
If set to 1
, TCP keepalive probes will be sent. The delay and
frequency of these probes can be controlled by theCURLOPT_TCP_KEEPIDLE
andCURLOPT_TCP_KEEPINTVL
options, provided the operating system
supports them. If set to0
(default) keepalive probes are disabled.Added in cURL 7.25.0. CURLOPT_TCP_KEEPIDLE
Sets the delay, in seconds, that the operating system will wait while the connection is
idle before sending keepalive probes, ifCURLOPT_TCP_KEEPALIVE
is
enabled. Not all operating systems support this option.
The default is60
.Added in cURL 7.25.0. CURLOPT_TCP_KEEPINTVL
Sets the interval, in seconds, that the operating system will wait between sending
keepalive probes, ifCURLOPT_TCP_KEEPALIVE
is enabled.
Not all operating systems support this option.
The default is60
.Added in cURL 7.25.0. CURLOPT_TIMECONDITION
How CURLOPT_TIMEVALUE
is treated.
UseCURL_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
assumingCURLOPT_HEADER
istrue
.
UseCURL_TIMECOND_IFUNMODSINCE
for the reverse
effect. UseCURL_TIMECOND_NONE
to ignore
CURLOPT_TIMEVALUE
and always return the page.
CURL_TIMECOND_NONE
is the default.Before cURL 7.46.0 the default was
CURL_TIMECOND_IFMODSINCE
.CURLOPT_TIMEOUT
The maximum number of seconds to allow cURL functions to execute. CURLOPT_TIMEOUT_MS
The maximum number of milliseconds to allow cURL functions to
execute.If libcurl is built to use the standard system name resolver, that
portion of the connect will still use full-second resolution for
timeouts with a minimum timeout allowed of one second.Added in cURL 7.16.2. CURLOPT_TIMEVALUE
The time in seconds since January 1st, 1970. The time will be used
byCURLOPT_TIMECONDITION
.CURLOPT_TIMEVALUE_LARGE
The time in seconds since January 1st, 1970. The time will be used
byCURLOPT_TIMECONDITION
. Defaults to zero.
The difference between this option andCURLOPT_TIMEVALUE
is the type of the argument. On systems where ‘long’ is only 32 bit wide,
this option has to be used to set dates beyond the year 2038.Added in cURL 7.59.0. Available since PHP 7.3.0. CURLOPT_MAX_RECV_SPEED_LARGE
If a download exceeds this speed (counted in bytes per second) on
cumulative average during the transfer, the transfer will pause to
keep the average rate less than or equal to the parameter value.
Defaults to unlimited speed.Added in cURL 7.15.5. CURLOPT_MAX_SEND_SPEED_LARGE
If an upload exceeds this speed (counted in bytes per second) on
cumulative average during the transfer, the transfer will pause to
keep the average rate less than or equal to the parameter value.
Defaults to unlimited speed.Added in cURL 7.15.5. CURLOPT_SSH_AUTH_TYPES
A bitmask consisting of one or more of
CURLSSH_AUTH_PUBLICKEY
,
CURLSSH_AUTH_PASSWORD
,
CURLSSH_AUTH_HOST
,
CURLSSH_AUTH_KEYBOARD
. Set to
CURLSSH_AUTH_ANY
to let libcurl pick one.Added in cURL 7.16.1. CURLOPT_IPRESOLVE
Allows an application to select what kind of IP addresses to use when
resolving host names. This is only interesting when using host names that
resolve addresses using more than one version of IP, possible values are
CURL_IPRESOLVE_WHATEVER
,
CURL_IPRESOLVE_V4
,
CURL_IPRESOLVE_V6
, by default
CURL_IPRESOLVE_WHATEVER
.Added in cURL 7.10.8. CURLOPT_FTP_FILEMETHOD
Tell curl which method to use to reach a file on a FTP(S) server. Possible values are
CURLFTPMETHOD_MULTICWD
,
CURLFTPMETHOD_NOCWD
and
CURLFTPMETHOD_SINGLECWD
.Added in cURL 7.15.1. value
should be a string for the
following values of theoption
parameter:Option Set value
toNotes CURLOPT_ABSTRACT_UNIX_SOCKET
Enables the use of an abstract Unix domain socket instead of
establishing a TCP connection to a host and sets the path to
the given string. This option shares the same semantics
asCURLOPT_UNIX_SOCKET_PATH
. These two options
share the same storage and therefore only one of them can be set
per handle.Available since PHP 7.3.0 and cURL 7.53.0 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
.Might require an absolute path. CURLOPT_CAPATH
A directory that holds multiple CA certificates. Use this option
alongsideCURLOPT_SSL_VERIFYPEER
.CURLOPT_COOKIE
The contents of the "Cookie: "
header to be
used in the HTTP request.
Note that 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.
If the name is an empty string, no cookies are loaded, but cookie
handling is still enabled.CURLOPT_COOKIEJAR
The name of a file to save all internal cookies to when the handle is closed,
e.g. after a call to curl_close.CURLOPT_COOKIELIST
A cookie string (i.e. a single line in Netscape/Mozilla format, or a regular
HTTP-style Set-Cookie header) adds that single cookie to the internal cookie store.
"ALL"
erases all cookies held in memory.
"SESS"
erases all session cookies held in memory.
"FLUSH"
writes all known cookies to the file specified byCURLOPT_COOKIEJAR
.
"RELOAD"
loads all cookies from the files specified byCURLOPT_COOKIEFILE
.Available since cURL 7.14.1. 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.0rnrn"
would be incorrect.Note:
Don’t do this without making sure the server supports the custom
request method first.CURLOPT_DEFAULT_PROTOCOL
The default protocol to use if the URL is missing a scheme name.
Added in cURL 7.45.0. Available since PHP 7.0.7. CURLOPT_DNS_INTERFACE
Set the name of the network interface that the DNS resolver should bind to.
This must be an interface name (not an address).Added in cURL 7.33.0. Available since PHP 7.0.7. CURLOPT_DNS_LOCAL_IP4
Set the local IPv4 address that the resolver should bind to. The argument
should contain a single numerical IPv4 address as a string.Added in cURL 7.33.0. Available since PHP 7.0.7. CURLOPT_DNS_LOCAL_IP6
Set the local IPv6 address that the resolver should bind to. The argument
should contain a single numerical IPv6 address as a string.Added in cURL 7.33.0. Available since PHP 7.0.7. 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 «PORT» instruction. The «PORT» 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_KEYPASSWD
The password required to use the CURLOPT_SSLKEY
orCURLOPT_SSH_PRIVATE_KEYFILE
private key.Added in cURL 7.16.1. 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 tonull
will disable KRB4 security. Currently KRB4 security only works
with FTP transactions.CURLOPT_LOGIN_OPTIONS
Can be used to set protocol specific login options, such as the
preferred authentication mechanism via «AUTH=NTLM» or «AUTH=*»,
and should be used in conjunction with the
CURLOPT_USERNAME
option.Added in cURL 7.34.0. Available since PHP 7.0.7. CURLOPT_PINNEDPUBLICKEY
Set the pinned public key.
The string can be the file name of your pinned public key. The file
format expected is «PEM» or «DER». The string can also be any
number of base64 encoded sha256 hashes preceded by «sha256//» and
separated by «;».Added in cURL 7.39.0. Available since PHP 7.0.7. CURLOPT_POSTFIELDS
The full data to post in a HTTP «POST» operation.
This parameter can either be
passed as a urlencoded string like ‘para1=val1¶2=val2&...
‘
or as an array with the field name as key and field data as value.
Ifvalue
is an array, the
Content-Type
header will be set to
multipart/form-data
.
Files can be sent using CURLFile or CURLStringFile,
in which casevalue
must be an array.
CURLOPT_PRIVATE
Any data that should be associated with this cURL handle. This data
can subsequently be retrieved with the
CURLINFO_PRIVATE
option of
curl_getinfo(). cURL does nothing with this data.
When using a cURL multi handle, this private data is typically a
unique key to identify a standard cURL handle.Added in cURL 7.10.3. CURLOPT_PRE_PROXY
Set a string holding the host name or dotted numerical
IP address to be used as the preproxy that curl connects to before
it connects to the HTTP(S) proxy specified in the
CURLOPT_PROXY
option for the upcoming request.
The preproxy can only be a SOCKS proxy and it should be prefixed with
[scheme]://
to specify which kind of socks is used.
A numerical IPv6 address must be written within [brackets].
Setting the preproxy to an empty string explicitly disables the use of a preproxy.
To specify port number in this string, append:[port]
to the end of the host name. The proxy’s port number may optionally be
specified with the separate optionCURLOPT_PROXYPORT
.
Defaults to using port 1080 for proxies if a port is not specified.Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. CURLOPT_PROXY
The HTTP proxy to tunnel requests through. CURLOPT_PROXY_SERVICE_NAME
The proxy authentication service name. Added in cURL 7.43.0 for HTTP proxies, and in cURL 7.49.0 for SOCKS5 proxies.
Available since PHP 7.0.7.CURLOPT_PROXY_CAINFO
The path to proxy Certificate Authority (CA) bundle. Set the path as a
string naming a file holding one or more certificates to
verify the HTTPS proxy with.
This option is for connecting to an HTTPS proxy, not an HTTPS server.
Defaults set to the system path where libcurl’s cacert bundle is assumed
to be stored.Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. CURLOPT_PROXY_CAPATH
The directory holding multiple CA certificates to verify the HTTPS proxy with. Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. CURLOPT_PROXY_CRLFILE
Set the file name with the concatenation of CRL (Certificate Revocation List)
in PEM format to use in the certificate validation that occurs during
the SSL exchange.Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. CURLOPT_PROXY_KEYPASSWD
Set the string be used as the password required to use the
CURLOPT_PROXY_SSLKEY
private key. You never needed a
passphrase to load a certificate but you need one to load your private key.
This option is for connecting to an HTTPS proxy, not an HTTPS server.Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. CURLOPT_PROXY_PINNEDPUBLICKEY
Set the pinned public key for HTTPS proxy. The string can be the file name
of your pinned public key. The file format expected is «PEM» or «DER».
The string can also be any number of base64 encoded sha256 hashes preceded by
«sha256//» and separated by «;»Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. CURLOPT_PROXY_SSLCERT
The file name of your client certificate used to connect to the HTTPS proxy.
The default format is «P12» on Secure Transport and «PEM» on other engines,
and can be changed withCURLOPT_PROXY_SSLCERTTYPE
.
With NSS or Secure Transport, this can also be the nickname of the certificate
you wish to authenticate with as it is named in the security database.
If you want to use a file from the current directory, please precede it with
«./» prefix, in order to avoid confusion with a nickname.Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. CURLOPT_PROXY_SSLCERTTYPE
The format of your client certificate used when connecting to an HTTPS proxy.
Supported formats are «PEM» and «DER», except with Secure Transport.
OpenSSL (versions 0.9.3 and later) and Secure Transport
(on iOS 5 or later, or OS X 10.7 or later) also support «P12» for
PKCS#12-encoded files. Defaults to «PEM».Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. CURLOPT_PROXY_SSL_CIPHER_LIST
The list of ciphers to use for the connection to the HTTPS proxy.
The list must be syntactically correct, it consists of one or more cipher
strings separated by colons. Commas or spaces are also acceptable separators
but colons are normally used, !, — and + can be used as operators.Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. CURLOPT_PROXY_TLS13_CIPHERS
The list of cipher suites to use for the TLS 1.3 connection to a proxy.
The list must be syntactically correct, it consists of one or more
cipher suite strings separated by colons. This option is currently used
only when curl is built to use OpenSSL 1.1.1 or later.
If you are using a different SSL backend you can try setting
TLS 1.3 cipher suites by using theCURLOPT_PROXY_SSL_CIPHER_LIST
option.Available since PHP 7.3.0 and libcurl >= cURL 7.61.0. Available when built with OpenSSL >= 1.1.1. CURLOPT_PROXY_SSLKEY
The file name of your private key used for connecting to the HTTPS proxy.
The default format is «PEM» and can be changed with
CURLOPT_PROXY_SSLKEYTYPE
.
(iOS and Mac OS X only) This option is ignored if curl was built against Secure Transport.Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. Available if built TLS enabled. CURLOPT_PROXY_SSLKEYTYPE
The format of your private key. Supported formats are «PEM», «DER» and «ENG». Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. CURLOPT_PROXY_TLSAUTH_PASSWORD
The password to use for the TLS authentication method specified with the
CURLOPT_PROXY_TLSAUTH_TYPE
option. Requires that the
CURLOPT_PROXY_TLSAUTH_USERNAME
option to also be set.Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. CURLOPT_PROXY_TLSAUTH_TYPE
The method of the TLS authentication used for the HTTPS connection. Supported method is «SRP». Note:
Secure Remote Password (SRP) authentication for TLS provides mutual authentication
if both sides have a shared secret. To use TLS-SRP, you must also set the
CURLOPT_PROXY_TLSAUTH_USERNAME
and
CURLOPT_PROXY_TLSAUTH_PASSWORD
options.Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. CURLOPT_PROXY_TLSAUTH_USERNAME
The username to use for the HTTPS proxy TLS authentication method specified with the
CURLOPT_PROXY_TLSAUTH_TYPE
option. Requires that the
CURLOPT_PROXY_TLSAUTH_PASSWORD
option to also be set.Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. 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_SERVICE_NAME
The authentication service name. Added in cURL 7.43.0. Available since PHP 7.0.7. CURLOPT_SSH_HOST_PUBLIC_KEY_MD5
A string containing 32 hexadecimal digits. The string should be the
MD5 checksum of the remote host’s public key, and libcurl will reject
the connection to the host unless the md5sums match.
This option is only for SCP and SFTP transfers.Added in cURL 7.17.1. CURLOPT_SSH_PUBLIC_KEYFILE
The file name for your public key. If not used, libcurl defaults to
$HOME/.ssh/id_dsa.pub if the HOME environment variable is set,
and just «id_dsa.pub» in the current directory if HOME is not set.Added in cURL 7.16.1. CURLOPT_SSH_PRIVATE_KEYFILE
The file name for your private key. If not used, libcurl defaults to
$HOME/.ssh/id_dsa if the HOME environment variable is set,
and just «id_dsa» in the current directory if HOME is not set.
If the file is password-protected, set the password with
CURLOPT_KEYPASSWD
.Added in cURL 7.16.1. CURLOPT_SSL_CIPHER_LIST
A list of ciphers to use for SSL. For example,
RC4-SHA
andTLSv1
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"
.
As of OpenSSL 0.9.3,"P12"
(for PKCS#12-encoded files)
is also supported.Added in cURL 7.9.3. CURLOPT_SSLENGINE
The identifier for the crypto engine of the private SSL key
specified inCURLOPT_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_TLS13_CIPHERS
The list of cipher suites to use for the TLS 1.3 connection. The list must be
syntactically correct, it consists of one or more cipher suite strings separated by colons.
This option is currently used only when curl is built to use OpenSSL 1.1.1 or later.
If you are using a different SSL backend you can try setting
TLS 1.3 cipher suites by using theCURLOPT_SSL_CIPHER_LIST
option.Available since PHP 7.3.0 and libcurl >= cURL 7.61.0. Available when built with OpenSSL >= 1.1.1. CURLOPT_UNIX_SOCKET_PATH
Enables the use of Unix domain sockets as connection endpoint and
sets the path to the given string.Added in cURL 7.40.0. Available since PHP 7.0.7. 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_USERNAME
The user name to use in authentication. Added in cURL 7.19.1. CURLOPT_PASSWORD
The password to use in authentication. Added in cURL 7.19.1. CURLOPT_USERPWD
A username and password formatted as
"[username]:[password]"
to use for the
connection.CURLOPT_XOAUTH2_BEARER
Specifies the OAuth 2.0 access token. Added in cURL 7.33.0. Available since PHP 7.0.7. value
should be an array for the
following values of theoption
parameter:Option Set value
toNotes CURLOPT_CONNECT_TO
Connect to a specific host and port instead of the URL’s host and port.
Accepts an array of strings with the format
HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT
.Added in cURL 7.49.0. Available since PHP 7.0.7. 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. CURLOPT_HTTPHEADER
An array of HTTP header fields to set, 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 has been performed.CURLOPT_PROXYHEADER
An array of custom HTTP headers to pass to proxies. Added in cURL 7.37.0. Available since PHP 7.0.7. CURLOPT_QUOTE
An array of FTP commands to execute on the server prior to the FTP
request.CURLOPT_RESOLVE
Provide a custom address for a specific host and port pair. An array
of hostname, port, and IP address strings, each element separated by
a colon. In the format:
array("example.com:80:127.0.0.1")
Added in cURL 7.21.3. value
should be a stream resource (using
fopen(), for example) for the following values of the
option
parameter:Option Set value
toCURLOPT_FILE
The file that the transfer should be written to. The default
isSTDOUT
(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 the name of a valid function or a Closure
for the following values of theoption
parameter:Option Set value
toNotes CURLOPT_HEADERFUNCTION
A callback accepting 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 by this callback. Return the number of
bytes written.CURLOPT_PASSWDFUNCTION
A callback accepting 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.Removed as of PHP 7.3.0. CURLOPT_PROGRESSFUNCTION
A callback accepting five parameters.
The first is the cURL resource, the second is the total number of
bytes expected to be downloaded in this transfer, the third is
the number of bytes downloaded so far, the fourth is the total
number of bytes expected to be uploaded in this transfer, and the
fifth is the number of bytes uploaded so far.Note:
The callback is only called when the
CURLOPT_NOPROGRESS
option is set tofalse
.Return a non-zero value to abort the transfer. In which case, the
transfer will set aCURLE_ABORTED_BY_CALLBACK
error.CURLOPT_READFUNCTION
A callback accepting three parameters.
The first is the cURL resource, the second is a
stream resource provided to cURL through the option
CURLOPT_INFILE
, and the third is the maximum
amount of data to be read. The callback must return a string
with a length equal or smaller than the amount of data requested,
typically by reading it from the passed stream resource. It should
return an empty string to signalEOF
.CURLOPT_WRITEFUNCTION
A callback accepting two parameters.
The first is the cURL resource, and the second is a
string with the data to be written. The data must be saved by
this callback. It must return the exact number of bytes written
or the transfer will be aborted with an error.CURLOPT_XFERINFOFUNCTION
A callback accepting two parameters.
Has a similar purpose asCURLOPT_PROGRESSFUNCTION
but is more modern
and the preferred option from cURL.Added in 7.32.0. Available as of PHP 8.2.0. Other values:
Option Set value
toCURLOPT_SHARE
A result of curl_share_init(). Makes the cURL
handle to use the data from the shared handle.
Return Values
Returns true
on success or false
on failure.
Changelog
Version | Description |
---|---|
8.0.0 |
handle expects a CurlHandleinstance now; previously, a resource was expected. |
7.3.15, 7.4.3 |
Introduced CURLOPT_HTTP09_ALLOWED .
|
7.3.0 |
Introduced CURLOPT_ABSTRACT_UNIX_SOCKET , CURLOPT_KEEP_SENDING_ON_ERROR ,CURLOPT_PRE_PROXY , CURLOPT_PROXY_CAINFO ,CURLOPT_PROXY_CAPATH , CURLOPT_PROXY_CRLFILE ,CURLOPT_PROXY_KEYPASSWD , CURLOPT_PROXY_PINNEDPUBLICKEY ,CURLOPT_PROXY_SSLCERT , CURLOPT_PROXY_SSLCERTTYPE ,CURLOPT_PROXY_SSL_CIPHER_LIST , CURLOPT_PROXY_SSLKEY ,CURLOPT_PROXY_SSLKEYTYPE , CURLOPT_PROXY_SSL_OPTIONS ,CURLOPT_PROXY_SSL_VERIFYHOST , CURLOPT_PROXY_SSL_VERIFYPEER ,CURLOPT_PROXY_SSLVERSION , CURLOPT_PROXY_TLSAUTH_PASSWORD ,CURLOPT_PROXY_TLSAUTH_TYPE , CURLOPT_PROXY_TLSAUTH_USERNAME ,CURLOPT_SOCKS5_AUTH , CURLOPT_SUPPRESS_CONNECT_HEADERS ,CURLOPT_DISALLOW_USERNAME_IN_URL , CURLOPT_DNS_SHUFFLE_ADDRESSES ,CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS , CURLOPT_HAPROXYPROTOCOL ,CURLOPT_PROXY_TLS13_CIPHERS , CURLOPT_SSH_COMPRESSION ,CURLOPT_TIMEVALUE_LARGE and CURLOPT_TLS13_CIPHERS .
|
7.0.7 |
Introduced CURL_HTTP_VERSION_2 , CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE ,CURL_HTTP_VERSION_2TLS , CURL_REDIR_POST_301 ,CURL_REDIR_POST_302 , CURL_REDIR_POST_303 ,CURL_REDIR_POST_ALL , CURL_VERSION_KERBEROS5 ,CURL_VERSION_PSL , CURL_VERSION_UNIX_SOCKETS ,CURLAUTH_NEGOTIATE , CURLAUTH_NTLM_WB ,CURLFTP_CREATE_DIR , CURLFTP_CREATE_DIR_NONE ,CURLFTP_CREATE_DIR_RETRY , CURLHEADER_SEPARATE ,CURLHEADER_UNIFIED , CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE ,CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE , CURLMOPT_MAX_HOST_CONNECTIONS ,CURLMOPT_MAX_PIPELINE_LENGTH , CURLMOPT_MAX_TOTAL_CONNECTIONS ,CURLOPT_CONNECT_TO , CURLOPT_DEFAULT_PROTOCOL ,CURLOPT_DNS_INTERFACE , CURLOPT_DNS_LOCAL_IP4 ,CURLOPT_DNS_LOCAL_IP6 , CURLOPT_EXPECT_100_TIMEOUT_MS ,CURLOPT_HEADEROPT , CURLOPT_LOGIN_OPTIONS ,CURLOPT_PATH_AS_IS , CURLOPT_PINNEDPUBLICKEY ,CURLOPT_PIPEWAIT , CURLOPT_PROXY_SERVICE_NAME ,CURLOPT_PROXYHEADER , CURLOPT_SASL_IR ,CURLOPT_SERVICE_NAME , CURLOPT_SSL_ENABLE_ALPN ,CURLOPT_SSL_ENABLE_NPN , CURLOPT_SSL_FALSESTART ,CURLOPT_SSL_VERIFYSTATUS , CURLOPT_STREAM_WEIGHT ,CURLOPT_TCP_FASTOPEN , CURLOPT_TFTP_NO_OPTIONS ,CURLOPT_UNIX_SOCKET_PATH , CURLOPT_XOAUTH2_BEARER ,CURLPROTO_SMB , CURLPROTO_SMBS ,CURLPROXY_HTTP_1_0 , CURLSSH_AUTH_AGENT andCURLSSLOPT_NO_REVOKE .
|
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($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);// grab URL and pass it to the browser
curl_exec($ch);// close cURL resource, and free up system resources
curl_close($ch);
?>
Notes
Note:
Passing an array to
CURLOPT_POSTFIELDS
will
encode the data as multipart/form-data,
while passing a URL-encoded string will encode the data as
application/x-www-form-urlencoded.
See Also
- curl_setopt_array() — Set multiple options for a cURL transfer
- CURLFile
- CURLStringFile
rmckay at webaware dot com dot au ¶
10 years ago
Please everyone, stop setting CURLOPT_SSL_VERIFYPEER to false or 0. If your PHP installation doesn't have an up-to-date CA root certificate bundle, download the one at the curl website and save it on your server:
http://curl.haxx.se/docs/caextract.html
Then set a path to it in your php.ini file, e.g. on Windows:
curl.cainfo=c:phpcacert.pem
Turning off CURLOPT_SSL_VERIFYPEER allows man in the middle (MITM) attacks, which you don't want!
joey ¶
7 years ago
It is important that anyone working with cURL and PHP keep in mind that not all of the CURLOPT and CURLINFO constants are documented. I always recommend reading the cURL documentation directly as it sometimes contains better information. The cURL API in tends to be fubar as well so do not expect things to be where you would normally logically look for them.
curl is especially difficult to work with when it comes to cookies. So I will talk about what I found with PHP 5.6 and curl 7.26.
If you want to manage cookies in memory without using files including reading, writing and clearing custom cookies then continue reading.
To start with, the way to enable in memory only cookies associated with a cURL handle you should use:
curl_setopt($curl, CURLOPT_COOKIEFILE, "");
cURL likes to use magic strings in options as special commands. Rather than having an option to enable the cookie engine in memory it uses a magic string to do that. Although vaguely the documentation here mentions this however most people like me wouldn't even read that because a COOKIEFILE is the complete opposite of what we want.
To get the cookies for a curl handle you can use:
curl_getinfo($curl, CURLINFO_COOKIELIST);
This will give an array containing a string for each cookie. It is tab delimited and unfortunately you will have to parse it yourself if you want to do anything beyond copying the cookies.
To clear the in memory cookies for a cURL handle you can use:
curl_setopt($curl, CURLOPT_COOKIELIST, "ALL");
This is a magic string. There are others in the cURL documentation. If a magic string isn't used, this field should take a cookie in the same string format as in getinfo for the cookielist constant. This can be used to delete individual cookies although it's not the most elegant API for doing so.
For copying cookies I recommend using curl_share_init.
You can also copy cookies from one handle to another like so:
foreach(curl_getinfo($curl_a, CURLINFO_COOKIELIST) as $cookie_line)
curl_setopt($curl, CURLOPT_COOKIELIST, $cookie_line);
An inelegant way to delete a cookie would be to skip the one you don't want.
I only recommend using COOKIELIST with magic strings because the cookie format is not secure or stable. You can inject tabs into at least path and name so it becomes impossible to parse reliably. If you must parse this then to keep it secure I recommend prohibiting more than 6 tabs in the content which probably isn't a big loss to most people.
A the absolute minimum for validation I would suggest:
/^([^t]+t){5}[^t]+$/D
Here is the format:
#define SEP "t" /* Tab separates the fields */
char *my_cookie =
"example.com" /* Hostname */
SEP "FALSE" /* Include subdomains */
SEP "/" /* Path */
SEP "FALSE" /* Secure */
SEP "0" /* Expiry in epoch time format. 0 == Session */
SEP "foo" /* Name */
SEP "bar"; /* Value */
Steve Kamerman ¶
11 years ago
If you want cURL to timeout in less than one second, you can use CURLOPT_TIMEOUT_MS, although there is a bug/"feature" on "Unix-like systems" that causes libcurl to timeout immediately if the value is < 1000 ms with the error "cURL Error (28): Timeout was reached". The explanation for this behavior is:
"If libcurl is built to use the standard system name resolver, that portion of the transfer will still use full-second resolution for timeouts with a minimum timeout allowed of one second."
What this means to PHP developers is "You can use this function without testing it first, because you can't tell if libcurl is using the standard system name resolver (but you can be pretty sure it is)"
The problem is that on (Li|U)nix, when libcurl uses the standard name resolver, a SIGALRM is raised during name resolution which libcurl thinks is the timeout alarm.
The solution is to disable signals using CURLOPT_NOSIGNAL. Here's an example script that requests itself causing a 10-second delay so you can test timeouts:
<?php
if (!isset($_GET['foo'])) {
// Client
$ch = curl_init('http://localhost/test/test_timeout.php?foo=bar');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
$data = curl_exec($ch);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
curl_close($ch);
if (
$curl_errno > 0) {
echo "cURL Error ($curl_errno): $curl_errorn";
} else {
echo "Data received: $datan";
}
} else {
// Server
sleep(10);
echo "Done.";
}
?>
Philippe dot Jausions at 11abacus dot com ¶
17 years ago
Clarification on the callback methods:
- CURLOPT_HEADERFUNCTION is for handling header lines received *in the response*,
- CURLOPT_WRITEFUNCTION is for handling data received *from the response*,
- CURLOPT_READFUNCTION is for handling data passed along *in the request*.
The callback "string" can be any callable function, that includes the array(&$obj, 'someMethodName') format.
-Philippe
ashw1 — at — no spam — post — dot — cz ¶
16 years ago
In case you wonder how come, that cookies don't work under Windows, I've googled for some answers, and here is the result: Under WIN you need to input absolute path of the cookie file.
This piece of code solves it:
<?php
if ($cookies != '')
{
if (substr(PHP_OS, 0, 3) == 'WIN')
{$cookies = str_replace('\','/', getcwd().'/'.$cookies);}
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookies);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookies);
}
?>
JScott jscott401 at gmail dot com ¶
12 years ago
Some additional notes for curlopt_writefunction. I struggled with this at first because it really isn't documented very well.
When you write a callback function and use it with curlopt_writefunction it will be called MULTIPLE times. Your function MUST return the ammount of data written to it each time. It is very picky about this. Here is a snippet from my code that may help you
<?php
curl_setopt($this->curl_handle, CURLOPT_WRITEFUNCTION, array($this, "receiveResponse"));// later on in the class I wrote my receive Response methodprivate function receiveResponse($curlHandle,$xmldata)
{
$this->responseString = $xmldata;
$this->responseXML .= $this->responseString;
$this->length = strlen($xmldata);
$this->size += $this->length;
return $this->length;
}
?>
Now I did this for a class. If you aren't doing OOP then you will obviously need to modify this for your own use.
CURL calls your script MULTIPLE times because the data will not always be sent all at once. Were talking internet here so its broken up into packets. You need to take your data and concatenate it all together until it is all written. I was about to pull my damn hair out because I would get broken chunks of XML back from the server and at random lengths. I finally figured out what was going on. Hope this helps
Ed Cradock ¶
13 years ago
PUT requests are very simple, just make sure to specify a content-length header and set post fields as a string.
Example:
<?php
function doPut($url, $fields)
{
$fields = (is_array($fields)) ? http_build_query($fields) : $fields;
if(
$ch = curl_init($url))
{
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields)));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return (int)
$status;
}
else
{
return false;
}
}
if(
doPut('http://example.com/api/a/b/c', array('foo' => 'bar')) == 200)
// do something
else
// do something else.
?>
You can grab the request data on the other side with:
<?php
if($_SERVER['REQUEST_METHOD'] == 'PUT')
{
parse_str(file_get_contents('php://input'), $requestData);
// Array ( [foo] => bar )
print_r($requestData);
// Do something with data...
}
?>
DELETE can be done in exactly the same way.
sgamon at yahoo dot com ¶
15 years ago
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/
Chris at PureFormSolutions dot com ¶
13 years ago
I've found that setting CURLOPT_HTTPHEADER more than once will clear out any headers you've set previously with CURLOPT_HTTPHEADER.
Consider the following:
<?php
# ...curl_setopt($cURL,CURLOPT_HTTPHEADER,array (
"Content-Type: text/xml; charset=utf-8",
"Expect: 100-continue"
));# ... do some other stuff ...curl_setopt($cURL,CURLOPT_HTTPHEADER,array (
"Accept: application/json"
));# ...
?>
Both the Content-Type and Expect I set will not be in the outgoing headers, but Accept will.
mw+php dot net at lw-systems dot de ¶
11 years ago
The description of the use of the CURLOPT_POSTFIELDS option should be emphasize, that using POST with HTTP/1.1 with cURL implies the use of a "Expect: 100-continue" header. Some web servers will not understand the handling of chunked transfer of post data.
To disable this behavior one must disable the use of the "Expect:" header with
curl_setopt($ch, CURLOPT_HTTPHEADER,array("Expect:"));
dweingart at pobox dot com ¶
20 years ago
If you want to Curl to follow redirects and you would also like Curl to echo back any cookies that are set in the process, use this:
<?php curl_setopt($ch, CURLOPT_COOKIEJAR, '-'); ?>
'-' means stdout
-dw
luca dot manzo at bbsitalia dot com ¶
17 years ago
If you're getting trouble with cookie handling in curl:
- curl manages tranparently cookies in a single curl session
- the option
<?php curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookieFileName"); ?>
makes curl to store the cookies in a file at the and of the curl session
- the option
<?php curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookieFileName"); ?>
makes curl to use the given file as source for the cookies to send to the server.
so to handle correctly cookies between different curl session, the you have to do something like this:
<?php
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE_PATH);
curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE_PATH);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($ch);
curl_close($ch);
return $result;
?>
in particular this is NECESSARY if you are using PEAR_SOAP libraries to build a webservice client over https and the remote server need to establish a session cookie. in fact each soap message is sent using a different curl session!!
I hope this can help someone
Luca
joelhy ¶
7 years ago
Please notice that CURLINFO_HEADER_OUT and CURLOPT_VERBOSE option does not work together:
"When CURLINFO_HEADER_OUT is set to TRUE than CURLOPT_VERBOSE does not work."(from https://bugs.php.net/bug.php?id=65348).
This took me an hour or two to figure it out.
cmatiasvillanueva at gmail dot com ¶
5 years ago
What is not mentioned in the documentation is that if you want to set a local-port or local-port-range to establish a connection is possible by adding CURLOPT_LOCALPORT and CURLOPT_LOCALPORTRANGE options.
Ex:
$conn=curl_init ('example.com');
curl_setopt($conn, CURLOPT_LOCALPORT, 35000);
curl_setopt($conn, CURLOPT_LOCALPORTRANGE, 200);
CURLOPT_LOCALPORT: This sets the local port number of the socket used for the connection.
CURLOPT_LOCALPORTRANGE: The range argument is the number of attempts libcurl will make to find a working local port number. It starts with the given CURLOPT_LOCALPORT and adds one to the number for each retry. Setting this option to 1 or below will make libcurl do only one try for the exact port number.
Interface can be also configured using CURLOPT_INTERFACE:
Ex:
curl_setopt($conn, CURLOPT_INTERFACE, "eth1");
yann dot corno at free dot fr ¶
20 years ago
About the CURLOPT_HTTPHEADER option, it took me some time to figure out how to format the so-called 'Array'. It fact, it is a list of strings. If Curl was already defining a header item, yours will replace it. Here is an example to change the Content Type in a POST:
<?php curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml")); ?>
Yann
ohcc at 163 dot com ¶
5 years ago
This is howto upload an existing file to an FTP server with cURL in PHP.
You should remember that CURLOPT_URL should contain the file's basename to save on the FTP server. For example, if you upload hello.txt to ftp://www.wuxiancheng.cn/text/, CURLOPT_URL should be ftp://www.wuxiancheng.cn/text/hello.txt rather than ftp://www.wuxiancheng.cn/text/, otherwise you will get an error message like "Uploading to a URL without a file name! " when you call curl_error();
<?php
$ch = curl_init();
$filepath = 'D:Webwwwwuxiancheng.cnhello.txt';
$basename = pathInfo($filepath, PATHINFO_BASENAME);
$filesize = fileSize($filepath);
curl_setopt_array(
$ch,
array(
CURLOPT_URL => 'ftp://www.wuxiancheng.cn/text/' . $basename,
CURLOPT_USERPWD => 'USERNAME:PASSWORD',
CURLOPT_PROTOCOLS => CURLPROTO_FTP,
CURLOPT_UPLOAD => true,
CURLOPT_INFILE => $filepath,
CURLOPT_INFILESIZE => $filesize,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
)
);
curl_exec($ch);
$message = curl_errno($ch) === CURLE_OK ? 'success' : 'failure';
echo $message;
?>
joeterranova at gmail dot com ¶
12 years ago
It appears that setting CURLOPT_FILE before setting CURLOPT_RETURNTRANSFER doesn't work, presumably because CURLOPT_FILE depends on CURLOPT_RETURNTRANSFER being set.
So do this:
<?php
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $fp);
?>
not this:
<?php
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
?>
anderseta at gmail dot com ¶
13 years ago
If you wish to find the size of the file you are streaming and use it as your header this is how:
<?php
function write_function($curl_resource, $string)
{
if(curl_getinfo($curl_resource, CURLINFO_SIZE_DOWNLOAD) <= 2000)
{
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Description: File Transfer');
header("Content-Transfer-Encoding: binary");
header("Content-Type: ".curl_getinfo($curl_resource, CURLINFO_CONTENT_TYPE)."");
header("Content-Length: ".curl_getinfo($curl_resource, CURLINFO_CONTENT_LENGTH_DOWNLOAD)."");
}
print
$string;
return
mb_strlen($string, '8bit');
}
?>
1440 is the the default number of bytes curl will call the write function (BUFFERSIZE does not affect this, i actually think you can not change this value), so it means the headers are going to be set only one time.
write_function must return the exact number of bytes of the string, so you can return a value with mb_strlen.
jade dot skaggs at gmail dot com ¶
15 years ago
After much struggling, I managed to get a SOAP request requiring HTTP authentication to work. Here's some source that will hopefully be useful to others.
<?php
$credentials
= "username:password";
// Read the XML to send to the Web Service
$request_file = "./SampleRequest.xml";
$fh = fopen($request_file, 'r');
$xml_data = fread($fh, filesize($request_file));
fclose($fh);
$url = "http://www.example.com/services/calculation";
$page = "/services/calculation";
$headers = array(
"POST ".$page." HTTP/1.0",
"Content-type: text/xml;charset="utf-8"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: "run"",
"Content-length: ".strlen($xml_data),
"Authorization: Basic " . base64_encode($credentials)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);
// Apply the XML to our curl call
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
$data = curl_exec($ch);
if (
curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
var_dump($data);
curl_close($ch);
}
?>
jancister at gmail dot com ¶
8 years ago
Please note that if you want to handle progress using CURLOPT_PROGRESSFUNCTION option, you need to take into consideration what version of PHP are you using. Since version 5.5.0, compatibility-breaking change was introduced in number/order of the arguments passed to the callback function, and cURL resource is now passed as first argument.
Prior to version 5.5.0:
<?php
// ...
curl_setopt($resource, CURLOPT_PROGRESSFUNCTION, 'progressCallback');
curl_setopt($resource, CURLOPT_NOPROGRESS, false);
// ...
function progressCallback($download_size = 0, $downloaded = 0, $upload_size = 0, $uploaded = 0)
{
// Handle progress
}
?>
From version 5.5.0:
<?php
// ...
curl_setopt($resource, CURLOPT_PROGRESSFUNCTION, 'progressCallback');
curl_setopt($resource, CURLOPT_NOPROGRESS, false);
// ...
function progressCallback($resource, $download_size = 0, $downloaded = 0, $upload_size = 0, $uploaded = 0)
{
// Handle progress
}
?>
However, if your code needs to be compatible with PHP version both before and after 5.5.0, consider adding a version check:
<?php
// ...
curl_setopt($resource, CURLOPT_PROGRESSFUNCTION, 'progressCallback');
curl_setopt($resource, CURLOPT_NOPROGRESS, false);
// ...
function progressCallback($resource, $download_size = 0, $downloaded = 0, $upload_size = 0, $uploaded = 0)
{
/**
* $resource parameter was added in version 5.5.0 breaking backwards compatibility;
* if we are using PHP version lower than 5.5.0, we need to shift the arguments
* @see http://php.net/manual/en/function.curl-setopt.php#refsect1-function.curl-setopt-changelog
*/
if (version_compare(PHP_VERSION, '5.5.0') < 0) {
$uploaded = $upload_size;
$upload_size = $downloaded;
$downloaded = $download_size;
$download_size = $resource;
}// Handle progress
}
?>
Aaron Wells ¶
8 years ago
If you use cURL to fetch user-supplied URLs (for instance, in a web-based RSS aggregator), be aware of the risk of server-side request forgery (SSRF). This is an attack where the user takes advantage of the fact that cURL requests are sent from the web server itself, to reach network locations they wouldn't be able to reach from outside the network.
For instance, they could enter a "http://localhost" URL, and access things on the web server via "localhost". Or, "ftp://localhost". cURL supports a lot of protocols!
If you are using CURLOPT_FOLLOWLOCATION, the malicious URL could be in a redirect from the original request. cURL also will follow redirect headers to other protocols! (303 See Other; Location: ftp://localhost).
So if you're using cURL with user-supplied URLs, at the very least use CURLOPT_PROTOCOLS (which also sets CURLOPT_REDIR_PROTOCOLS), and either disable CURLOPT_FOLLOWLOCATION or use the "SafeCurl" library to safely follow redirects.
badman ¶
9 years ago
Many hosters use PHP safe_mode or/and open_basedir, so you can't use CURLOPT_FOLLOWLOCATION. If you try, you see message like this:
CURLOPT_FOLLOWLOCATION cannot be activated when safe_mode is enabled or an open_basedir is set in [you script name & path] on line XXX
First, I try to use zsalab function (http://us2.php.net/manual/en/function.curl-setopt.php#102121) from this page, but for some reason it did not work properly. So, I wrote my own.
It can be use instead of curl_exec. If server HTTP response codes is 30x, function will forward the request as long as the response is not different from 30x (for example, 200 Ok). Also you can use POST.
function curlExec(/* Array */$curlOptions='', /* Array */$curlHeaders='', /* Array */$postFields='')
{
$newUrl = '';
$maxRedirection = 10;
do
{
if ($maxRedirection<1) die('Error: reached the limit of redirections');
$ch = curl_init();
if (!empty($curlOptions)) curl_setopt_array($ch, $curlOptions);
if (!empty($curlHeaders)) curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeaders);
if (!empty($postFields))
{
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
}
if (!empty($newUrl)) curl_setopt($ch, CURLOPT_URL, $newUrl); // redirect needed
$curlResult = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302 || $code == 303 || $code == 307)
{
preg_match('/Location:(.*?)n/', $curlResult, $matches);
$newUrl = trim(array_pop($matches));
curl_close($ch);
$maxRedirection--;
continue;
}
else // no more redirection
{
$code = 0;
curl_close($ch);
}
}
while($code);
return $curlResult;
}
rob at infoglobe dot net ¶
16 years ago
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.
skyogre __at__ yandex __dot__ ru ¶
17 years ago
There is really a problem of transmitting $_POST data with curl in php 4+ at least.
I improved the encoding function by Alejandro Moreno to work properly with mulltidimensional arrays.
<?php
function data_encode($data, $keyprefix = "", $keypostfix = "") {
assert( is_array($data) );
$vars=null;
foreach($data as $key=>$value) {
if(is_array($value)) $vars .= data_encode($value, $keyprefix.$key.$keypostfix.urlencode("["), urlencode("]"));
else $vars .= $keyprefix.$key.$keypostfix."=".urlencode($value)."&";
}
return $vars;
}curl_setopt($ch, CURLOPT_POSTFIELDS, substr(data_encode($_POST), 0, -1) );?>
fnjordy at gmail dot com ¶
14 years ago
Note that CURLOPT_RETURNTRANSFER when used with CURLOPT_WRITEFUNCTION has effectively three settings: default, true, and false.
default - callbacks will be called as expected.
true - content will be returned but callback function will not be called.
false - content will be output and callback function will not be called.
Note that CURLOPT_HEADERFUNCTION callbacks are always called.
juozaspo at gmail dot com ¶
10 years ago
I've created an example that gets the file on url passed to script and outputs it to the browser.
<?php
//get the file (e.g. image) and output it to the browser
$ch = curl_init(); //open curl handle
curl_setopt($ch, CURLOPT_URL, $_GET['url']); //set an url
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //do not output directly, use variable
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); //do a binary transfer
curl_setopt($ch, CURLOPT_FAILONERROR, 1); //stop if an error occurred
$file=curl_exec($ch); //store the content in variable
if(!curl_errno($ch))
{
//send out headers and output
header ("Content-type: ".curl_getinfo($ch, CURLINFO_CONTENT_TYPE)."");
header ("Content-Length: ".curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD)."");
echo $file;
} else echo 'Curl error: ' . curl_error($ch);
curl_close($ch); //close curl handle
?>
p.s. Make sure that there're no new lines before and after code or script may not work.
Joey Hewitt ¶
11 years ago
Ojas Ojasvi ¶
15 years ago
<?php
/*
* Author: Ojas Ojasvi
* Released: September 25, 2007
* Description: An example of the disguise_curl() function in order to grab contents from a website while remaining fully camouflaged by using a fake user agent and fake headers.
*/
$url = 'http://www.php.net';
// disguises the curl using fake headers and a fake user agent.
function disguise_curl($url)
{
$curl = curl_init();
// Setup headers - I used the same headers from Firefox version 2.0.0.6
// below was split up because php.net said the line was too long. :/
$header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
$header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
$header[] = "Cache-Control: max-age=0";
$header[] = "Connection: keep-alive";
$header[] = "Keep-Alive: 300";
$header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
$header[] = "Accept-Language: en-us,en;q=0.5";
$header[] = "Pragma: "; // browsers keep this blank.
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($curl, CURLOPT_AUTOREFERER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
$html = curl_exec($curl); // execute the curl command
curl_close($curl); // close the connection
return $html; // and finally, return $html
}
// uses the function and displays the text off the website
$text = disguise_curl($url);
echo $text;
?>
Ojas Ojasvi
S ¶
12 years ago
When using CURLOPT_POSTFIELDS with an array as parameter, you have to pay high attention to user input. Unvalidated user input will lead to serious security issues.
<?php/**
* test.php:
*/
$ch = curl_init('http://example.com');curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'foo' => $_GET['bar']
));curl_exec($ch);?>
Requesting "test.php?bar=@/home/user/test.png" will send "test.png" to example.com.
Make sure you remove the leading "@" from user input.
PHP at RHaworth dot net ¶
12 years ago
When CURLOPT_FOLLOWLOCATION and CURLOPT_HEADER are both true and redirect/s have happened then the header returned by curl_exec() will contain all the headers in the redirect chain in the order they were encountered.
Dustin Hawkins ¶
17 years ago
To further expand upon use of CURLOPT_CAPATH and CURLOPT_CAINFO...
In my case I wanted to prevent curl from talking to any HTTPS server except my own using a self signed certificate. To do this, you'll need openssl installed and access to the HTTPS Server Certificate (server.crt by default on apache)
You can then use a command simiar to this to translate your apache certificate into one that curl likes.
$ openssl x509 -in server.crt -out outcert.pem -text
Then set CURLOPT_CAINFO equal to the the full path to outcert.pem and turn on CURLOPT_SSL_VERIFYPEER.
If you want to use the CURLOPT_CAPATH option, you should create a directory for all the valid certificates you have created, then use the c_rehash script that is included with openssl to "prepare" the directory.
If you dont use the c_rehash utility, curl will ignore any file in the directory you set.
saidk at phirebranding dot com ¶
14 years ago
Passing in PHP's $_SESSION into your cURL call:
<?php
session_start();
$strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/';
session_write_close();
$curl_handle = curl_init('enter_external_url_here');
curl_setopt( $curl_handle, CURLOPT_COOKIE, $strCookie );
curl_exec($curl_handle);
curl_close($curl_handle);
?>
This worked great for me. I was calling pages from the same server and needed to keep the $_SESSION variables. This passes them over. If you want to test, just print_r($_SESSION);
Enjoy!
Martin K. ¶
9 years ago
If you only want to enable cookie handling and you don't need to save the cookies for a separate session, just set CURLOPT_COOKIEFILE to an empty string. I was given the advice to use php://memory but that did not seem to have the same effect.
Although this is stated in the documentation I thought it was worth reiterating since it cause me so much trouble.
mr at coder dot tv ¶
17 years ago
Sometimes you can't use CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE becoz of the server php-settings(They say u may grab any files from server using these options). Here is the solution
1)Don't use CURLOPT_FOLLOWLOCATION
2)Use curl_setopt($ch, CURLOPT_HEADER, 1)
3)Grab from the header cookies like this:
preg_match_all('|Set-Cookie: (.*);|U', $content, $results);
$cookies = implode(';', $results[1]);
4)Set them using curl_setopt($ch, CURLOPT_COOKIE, $cookies);
Good Luck, Yevgen
qwertz182 ¶
2 years ago
As the "example #2 Uploading file" says it is deprecated as of PHP 5.5.0 but doesn't tell you how it's done right,
here is a really easy example using the CURLFile class:
<?php
$request = [
'firstName' => 'John',
'lastName' => 'Doe',
'file' => new CURLFile('example.txt', 'text/plain') // or use curl_file_create()
];$curlOptions = [
CURLOPT_URL => 'http://example.com/upload.php',
CURLOPT_POST => true,
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $request,
];$ch = curl_init();
curl_setopt_array($ch, $curlOptions);$response = curl_exec($ch);
?>
This is just like posting a html form with an input[type=file] field.
The result on windows could look like this:
<?php
// $_POST
Array
(
[firstName] => John
[lastName] => Doe
)// $_FILES
Array
(
[file] => Array
(
[name] => example.txt
[type] => text/plain
[tmp_name] => C:wamp64tmpphp3016.tmp
[error] => 0
[size] => 14
)
)
?>
Since the request is an array (and not a string), curl will automatically encode the data as "multipart/form-data".
Please be aware that if you pass an invalid file path to CURLFile, setting the CURLOPT_POSTFIELDS option will fail.
So if you are using curl_setopt_array for setting the options at once, according to the manual, "If an option could not be successfully set, FALSE is immediately returned, ignoring any future options in the options array.".
So you should make sure that the file exists or set CURLOPT_POSTFIELDS with curl_setopt() and check if it returns false and act accordingly.
eric dot van dot eldik at peercode dot nl ¶
4 years ago
When you get this error using a PUT request: "SSL read: error:00000000:lib(0):func(0):reason(0), errno 104")
It could be caused by:
<?php
curl_setopt($ch, CURLOPT_PUT, TRUE);
?>
Instead try:
<?php
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
?>
regan dot corey at gmail dot com ¶
10 years ago
I spent a couple of days trying to POST a multi-dimensional array of form fields, including a file upload, to a remote server to update a product. Here are the breakthroughs that FINALLY allowed the script to run as desired.
Firstly, the HTML form used input names like these:
<input type="text" name="product[name]" />
<input type="text" name="product[cost]" />
<input type="file" name="product[thumbnail]" />
in conjunction with two other form inputs not part of the product array
<input type="text" name="method" value="put" />
<input type="text" name="mode" />
I used several cURL options, but the only two (other than URL) that mattered were:
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $postfields);
Pretty standard so far.
Note: headers didn't need to be set, cURL automatically sets headers (like content-type: multipart/form-data; content-length...) when you pass an array into CURLOPT_POSTFIELDS.
Note: even though this is supposed to be a PUT command through an HTTP POST form, no special PUT options needed to be passed natively through cURL. Options such as
curl_setopt($handle, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT', 'Content-Length: ' . strlen($fields)));
or
curl_setopt($handle, CURLOPT_PUT, true);
or
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "PUT);
were not needed to make the code work.
The fields I wanted to pass through cURL were arranged into an array something like this:
$postfields = array("method" => $_POST["method"],
"mode" => $_POST["mode"],
"product" => array("name" => $_POST["product"],
"cost" => $_POST["product"]["cost"],
"thumbnail" => "@{$_FILES["thumbnail"]["tmp_name"]};type={$_FILES["thumbnail"]["type"]}")
);
-Notice how the @ precedes the temporary filename, this creates a link so PHP will upload/transfer an actual file instead of just the file name, which would happen if the @ isn't included.
-Notice how I forcefully set the mime-type of the file to upload. I was having issues where images filetypes were defaulting to octet-stream instead of image/png or image/jpeg or whatever the type of the selected image.
I then tried passing $postfields straight into curl_setopt($this->handle, CURLOPT_POSTFIELDS, $postfields); but it didn't work.
I tried using http_build_query($postfields); but that didn't work properly either.
In both cases either the file wouldn't be treated as an actual file and the form data wasn't being sent properly. The problem was HTTP's methods of transmitting arrays. While PHP and other languages can figure out how to handle arrays passed via forms, HTTP isn't quite as sofisticated. I had to rewrite the $postfields array like so:
$postfields = array("method" => $_POST["method"],
"mode" => $_POST["mode"],
"product[name]" => $_POST["product"],
"product[cost]" => $_POST["product"]["cost"],
"product[thumbnail]" => "@{$_FILES["thumbnail"]["tmp_name"]}");
curl_setopt($handle, CURLOPT_POSTFIELDS, $postfields);
This, without the use of http_build_query, solved all of my problems. Now the receiving host outputs both $_POST and $_FILES vars correctly.
JM ¶
4 years ago
Note that CURLOPT_TIMEOUT takes integers, so you cannot use it to set a timeout smaller than one second.
scy-phpmanual at scytale dot name ¶
12 years ago
In order to reset CURLOPT_HTTPHEADER, set it to array(). The cURL C API says you should set it to NULL, but that doesn’t work in the PHP wrapper.
gskluzacek at gmail dot com ¶
12 years ago
FYI... unless you specifically set the user agent, no user agent will be sent in your request as there is no default value like some of the other options.
As others have said, not sending a user agent may cause you to not get the results that you expected, e.g., 0 byte length content, different content, etc.
Pawel Antczak ¶
13 years ago
Hello.
During problems with "CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set"
I was looking for solution.
I've found few methods on this page, but none of them was good enough, so I made one.
<?php
function curl_redirect_exec($ch, &$redirects, $curlopt_header = false) {
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code == 301 || $http_code == 302) {
list($header) = explode("rnrn", $data, 2);
$matches = array();
preg_match('/(Location:|URI:)(.*?)n/', $header, $matches);
$url = trim(array_pop($matches));
$url_parsed = parse_url($url);
if (isset($url_parsed)) {
curl_setopt($ch, CURLOPT_URL, $url);
$redirects++;
return curl_redirect_exec($ch, $redirects);
}
}
if ($curlopt_header)
return $data;
else {
list(,$body) = explode("rnrn", $data, 2);
return $body;
}
}
?>
Main issue in existing functions was lack of information, how many redirects was done.
This one will count it.
First parameter as usual.
Second should be already initialized integer, it will be incremented by number of done redirects.
You can set CURLOPT_HEADER if You need it.
michaeledwards.com ¶
18 years ago
Problems can occur if you mix CURLOPT_URL with a 'Host:' header in CURLOPT_HEADERS on redirects because cURL will combine the host you explicitly stated in the 'Host:' header with the host from the Location: header of the redirect response.
In short, don't do this:
<?php
$host = "www.example.com";
$url = "http://$host/";
$headers = array("Host: $host");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
Do
this instead:
$host = "www.example.com";
$url = "http://$host/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
?>
zsalab ¶
12 years ago
Handling redirections with curl if safe_mode or open_basedir is enabled. The function working transparent, no problem with header and returntransfer options. You can handle the max redirection with the optional second argument (the function is set the variable to zero if max redirection exceeded).
Second parameter values:
- maxredirect is null or not set: redirect maximum five time, after raise PHP warning
- maxredirect is greather then zero: no raiser error, but parameter variable set to zero
- maxredirect is less or equal zero: no follow redirections
<?php
function curl_exec_follow(/*resource*/ $ch, /*int*/ &$maxredirect = null) {
$mr = $maxredirect === null ? 5 : intval($maxredirect);
if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $mr > 0);
curl_setopt($ch, CURLOPT_MAXREDIRS, $mr);
} else {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
if ($mr > 0) {
$newurl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$rch = curl_copy_handle($ch);
curl_setopt($rch, CURLOPT_HEADER, true);
curl_setopt($rch, CURLOPT_NOBODY, true);
curl_setopt($rch, CURLOPT_FORBID_REUSE, false);
curl_setopt($rch, CURLOPT_RETURNTRANSFER, true);
do {
curl_setopt($rch, CURLOPT_URL, $newurl);
$header = curl_exec($rch);
if (curl_errno($rch)) {
$code = 0;
} else {
$code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302) {
preg_match('/Location:(.*?)n/', $header, $matches);
$newurl = trim(array_pop($matches));
} else {
$code = 0;
}
}
} while ($code && --$mr);
curl_close($rch);
if (!$mr) {
if ($maxredirect === null) {
trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
} else {
$maxredirect = 0;
}
return false;
}
curl_setopt($ch, CURLOPT_URL, $newurl);
}
}
return curl_exec($ch);
}
?>
c00lways at gmail dot com ¶
15 years ago
if you would like to send xml request to a server (lets say, making a soap proxy),
you have to set
<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
?>
makesure you watch for cache issue:
the below code will prevent cache...
<?php
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
?>
hope it helps ;)
Adam Monsen ¶
11 years ago
CURLOPT_POST must be left unset if you want the Content-Type header set to "multipart/form-data" (e.g., when CURLOPT_POSTFIELDS is an array). If you set CURLOPT_POSTFIELDS to an array and have CURLOPT_POST set to TRUE, Content-Length will be -1 and most sane servers will reject the request. If you set CURLOPT_POSTFIELDS to an array and have CURLOPT_POST set to FALSE, cURL will send a GET request.
ron at ttvavanti dot nl ¶
19 years ago
If you specify a CAINFO, note that the file must be in PEM format! (If not, it won't work).
Using Openssl you can use:
openssl x509 -in <cert> -inform d -outform PEM -out cert.pem
To create a pem formatted certificate from a binary certificate (the one you get if you download the ca somewhere).
fred at themancan dot com ¶
14 years ago
To find what encoding a given HTTP POST request uses 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.
clint at fewbar dot com ¶
13 years ago
If you have turned on conditional gets on a curl handle, and then for a subsequent request, you don't have a good setting for CURLOPT_TIMEVALUE , you can disable If-Modified-Since checking with:
<?php
$ch
= curl_init();
curl_setopt($ch, CURLOPT_URL, $foo);
curl_setopt($ch, CURLOPT_TIMEVALUE, filemtime($foo_path));
curl_setopt($ch, CURLOPT_TIMECONDITION, CURLOPT_TIMECOND_IFMODIFIEDSINCE);
curl_exec($ch);
// Reuse same curl handle
curl_setopt($ch, CURLOPT_URL, $bar);
curl_setopt($ch, CURLOPT_TIMEVALUE, null); // don't know mtime
curl_setopt($ch, CURLOPT_TIMECONDITION, 0); // set it to 0, turns it off
curl_exec($ch);?>
rob ¶
13 years ago
Whats not mentioned in the documentation is that you have to set CURLOPT_COOKIEJAR to a file for the CURL handle to actually use cookies, if it is not set then cookies will not be parsed.
xektrum at gmail dot com ¶
13 years ago
As of php 5.3 CURLOPT_PROGRESSFUNCTION its supported here's how:
<?phpfunction callback($download_size, $downloaded, $upload_size, $uploaded)
{
// do your progress stuff here
}$ch = curl_init('http://www.example.com');// This is required to curl give us some progress
// if this is not set to false the progress function never
// gets called
curl_setopt($ch, CURLOPT_NOPROGRESS, false);// Set up the callback
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'callback');// Big buffer less progress info/callbacks
// Small buffer more progress info/callbacks
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);$data = curl_exec($ch);?>
Hope this help.
markandrewslade at gmail dot com ¶
6 years ago
Contrary to the documentation, CURLOPT_STDERR should be set to a handle to the file you want to write to, not the file's location.
eion at bigfoot dot com ¶
16 years ago
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("nn", $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;
}
}
?>
shiplu at programmer dot net ¶
10 years ago
CURLOPT_POST should be set before CURLOPT_POSTFIELDS. Otherwise you might encounter 411 Length required error.
Following code generates "411 Length Required" on nginx/1.1.15
<?php
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt ($ch, CURLOPT_POST, 1);
?>
But this one works.
<?php
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postfields);
?>
Sylvain R ¶
13 years ago
When you are using CURLOPT_FILE to download directly into a file you must close the file handler after the curl_close() otherwise the file will be incomplete and you will not be able to use it until the end of the execution of the php process.
<?php
$fh
= fopen('/tmp/foo', 'w');
$ch = curl_init('http://example.com/foo');
curl_setopt($ch, CURLOPT_FILE, $fh);
curl_exec($ch);
curl_close($ch);
# at this point your file is not complete and corrupted
fclose($fh);
# now you can use your file;
read_file('/tmp/foo');
?>
Salil Kothadia ¶
14 years ago
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);
?>
Tyranoweb ¶
13 years ago
There is a function to send POST data in page with five parameters :
$post must be an array
$page is the page where POST datas will be send.
$n must be true to continue if they are php redirection (Location: )
$session must be define true if you want to use cookies
$referer must be a link to get a wrong referer or only to have a referer.
<?php
function curl_data_post($post, $page, $n, $session, $referer)
{
if(!is_array($post))
{
return false;
}
$DATA_POST = curl_init();
curl_setopt($DATA_POST, CURLOPT_RETURNTRANSFER, true);
curl_setopt($DATA_POST, CURLOPT_URL, $page);
curl_setopt($DATA_POST, CURLOPT_POST, true);
if($n)
{
curl_setopt($DATA_POST, CURLOPT_FOLLOWLOCATION, true);
}
if($session)
{
curl_setopt($DATA_POST, CURLOPT_COOKIEFILE, 'cookiefile.txt');
curl_setopt($DATA_POST, CURLOPT_COOKIEJAR, 'cookiefile.txt');
}
if(
$referer)
{
curl_setopt($DATA_POST, CURLOPT_REFERER, $referer);
}
curl_setopt($DATA_POST, CURLOPT_POSTFIELDS, $post);
$data = curl_exec($DATA_POST);
if($data == false)
{
echo'Warning : ' . curl_error($DATA_POST);
curl_close($DATA_POST);
return false;
}
else
{
curl_close($DATA_POST);
return $data;
}
}
?>
php at miggy dot org ¶
16 years ago
Note that if you want to use a proxy and use it as a _cache_, you'll have to do:
<?php 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.
tim dot php at ebw dot ca ¶
19 years ago
joel at mojamail dot com ¶
5 years ago
In the long documentation, it's easy to miss the fact that CURLOPT_POSTFIELDS will set the Content-Type to "multipart/form-data" (instead of the usual "application/x-www-form-urlencoded") IFF you supply an array (instead of a query string)!
Some servers will return weird errors (like "SSL read: error:00000000:lib(0):func(0):reason(0), errno 104") for the wrong Content-Type, and you may waste many hours of time trying to figure out why!
Richard ¶
8 years ago
CURL_SSLVERSION_TLSv1_0 (4), CURL_SSLVERSION_TLSv1_1 (5) or CURL_SSLVERSION_TLSv1_2 (6) only work for PHP versions using curl 7.34 or newer.
ROXORT at TGNOOB dot FR ¶
17 years ago
<?php
/*
Here is a script that is usefull to :
- login to a POST form,
- store a session cookie,
- download a file once logged in.
*/
// INIT CURL
$ch = curl_init();
// SET URL FOR THE POST FORM LOGIN
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/Members/Login.php');
// ENABLE HTTP POST
curl_setopt ($ch, CURLOPT_POST, 1);
// SET POST PARAMETERS : FORM VALUES FOR EACH FIELD
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'fieldname1=fieldvalue1&fieldname2=fieldvalue2');
// IMITATE CLASSIC BROWSER'S BEHAVIOUR : HANDLE COOKIES
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
# Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
# not to print out the results of its query.
# Instead, it will return the results as a string return value
# from curl_exec() instead of the usual true/false.
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
// EXECUTE 1st REQUEST (FORM LOGIN)
$store = curl_exec ($ch);
// SET FILE TO DOWNLOAD
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/Members/Downloads/AnnualReport.pdf');
// EXECUTE 2nd REQUEST (FILE DOWNLOAD)
$content = curl_exec ($ch);
// CLOSE CURL
curl_close ($ch);
/*
At this point you can do do whatever you want
with the downloaded file stored in $content :
display it, save it as file, and so on.
*/
?>
anonymous ¶
11 years ago
This may be not obvious, but if you specify the CURLOPT_POSTFIELDS and don't specify the CURLOPT_POST - it will still send POST, not GET (as you might think - since GET is default).
So the line:
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
is synonym to:
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
Even if you set the options like this (in this order):
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
it will send POST, since CURLOPT_POSTFIELDS is latter.
So if you want GET - make sure you don't have CURLOPT_POSTFIELDS specified somewhere.
dotpointer at gmail dot com ¶
11 years ago
I noted something when using CURLOPT_POSTFIELDS in combination with arrays from PHP.
You may supply an array, but there may not be any sub-arrays in this array, as this will give Array-to-string-conversion notice.
Example:
<?php
$ch = curl_init();
# this works
$data = array('name' => 'value');
# this gives "Notice: Array to string conversion..."
$data = array('name' => array('subname' => 'subvalue'));
curl_setopt($ch, CURLOPT_URL, 'http://localhost/test.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
?>
paczor ¶
16 years ago
How to get rid of response after POST: just add callback function for returned data (CURLOPT_WRITEFUNCTION) and make this function empty.
<?php
function curlHeaderCallback($ch, $strHeader) {
}
curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'curlHeaderCallback');
?>
Madcat ¶
10 years ago
If you have a mixture of strings starting with @ (at character) and files in CURLOPT_POSTFIELDS you have a problem (such as posting a tweet with attached media) because curl tries to interpret anything starting with @ as a file.
<?php
$postfields
= array(
'upload_file' => '@file_to_upload.png',
'upload_text' => '@text_to_upload'
);$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://example.com/upload-test');
curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
curl_exec($curl);
curl_close($curl);?>
To get around this, prepend the text string with the NULL character like so:
<?php
$postfields = array(
'upload_file' => '@file_to_upload.png',
'upload_text' => sprintf("%s", '@text_to_upload')
);
?>
Original source: http://bit.ly/AntMle
ac at an dot y-co dot de ¶
14 years ago
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, '2');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, '1');
curl_setopt($ch, CURLOPT_CAINFO, getcwd().'/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
qeremy [atta] gmail [dotta] com ¶
10 years ago
If you are trying to update something on your server and you need to handle this update operation by PUT;
<?php
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_PUT, 1);
?>
are "useless" without;
<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT'));
?>
Example;
Updating a book data in database identified by "id 1";
--cURL Part--
<?php
$data = http_build_query($_POST);
// or
$data = http_build_query(array(
'name' => 'PHP in Action',
'price' => 10.9
));$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.localhost/rest/books/1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // no need anymore
// or
// curl_setopt($ch, CURLOPT_PUT, 1); // no need anymore
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$ce = curl_exec($ch);
curl_close($ch);
print_r($ce);
?>
--API class--
<?php
public function putAction() {
echo "putAction() -> id: ". $this->_getParam('id') ."n";
print_r($_POST);
// do stuff with post data
...
?>
--Output--
putAction() -> id: 15
Array
(
[name] => PHP in Action
[price] => 10.9
)
---Keywords--
rest, restfull api, restfull put, curl put, curl customrequest put
sam at def dot reyssi dot net ¶
12 years ago
Be careful when setting the CURLOPT_POSTFIELDS setting using an array. The array used to set the POST fields must only contain scalar values. Multidimentional arrays or objects lacking a __toString implementation will cause Curl to error.
If there is a need to send non-scalar values using a POST request, consider serializing them before transmission.
<?php
$ch = curl_init('http://host.example.com');
// Data to post
$multiDimensional = array(
'name' = 'foo',
'data' = array(1,2,3,4),
'value' = 'bar'
);
// Will error
curl_setopt($ch, CURLOPT_POSTFIELDS, $multiDimensional);
// Data to post
$postData = array(
'name' = 'foo',
'data' = serialize(array(1,2,3,4)),
'value' = 'bar'
);
// Will not error
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
?>
starosielec at googlemail dot com ¶
13 years ago
You can use also use object methods as callback functions. This is usefull if your curl ressource is part of an object handling transfers.
Instead of curl_setopt($curl, CURLOPT_WRITEFUNCTION, "curl_handler_recv") you can use array($object, "method") as value for callback options.
For example:
<?php
class downloader {
private $curl;
function
__construct() {
$this->curl = curl_init();
curl_setopt($this->curl, CURLOPT_WRITEFUNCTION, array($this, "curl_handler_recv"));
}
function
curl_handler_recv($res, $data) {
//...
}
//...
}
?>
m at mar dot lt ¶
10 years ago
Be careful when changing CURLOPT_SSL_VERIFYHOST or other options to true (boolean). It may cause insecure behavior [1]
This is because boolean true casts into integer 1, and CURLOPT_SSL_VERIFYHOST = 1 is not secure behavior.
The *correct* value here is CURLOPT_SSL_VERIFYHOST = 2. By setting this value equal to 1 the peer certificate must contain a Common Name field, but it doesn't matter what name it says.
[1] Martin Georgiev and Subodh Iyengar and Suman Jana and Rishita Anubhai and Dan Boneh and Vitaly Shmatikov, The most dangerous code in the world: validating SSL certificates in non-browser software, ACM CCS '12, pp. 38-49, 2012
phpnet at wafflehouse dot de ¶
17 years ago
Resetting CURLOPT_FILE to STDOUT won't work by calling curl_setopt() with the STDOUT constant or a php://output stream handle (at least I get error messages when trying the code from phpnet at andywaite dot com). Instead, one can simply reset it as a side effect of CURLOPT_RETURNTRANSFER. Just say
<?php curl_setopt($this->curl,CURLOPT_RETURNTRANSFER,0); ?>
and following calls to curl_exec() will output to STDOUT again.
mavook at gmail dot com ¶
15 years ago
If you try to upload file to a server, you need do CURLOPT_POST first and then fill CURLOPT_POSTFIELDS.
<?php
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
// ^^ This will post multipart/form-data
?>
Tim Severien ¶
11 years ago
I've been stuck when using the CURLOPT_CONNECTTIMEOUT_MS constant. In fact, on my PHP version (5.3.1) it's not a number but rather a string. Same thing for CURLOPT_TIMEOUT_MS.
I got this error: Warning: curl_setopt() expects parameter 2 to be long, string given
If you are experiencing simular problems, you can replace the constant with the actual number or (re)define the constant.
CURLOPT_TIMEOUT_MS should be 155
CURLOPT_CONNECTTIMEOUT_MS should be 156
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 2500); // error
curl_setopt($ch, 156, 2500); // problem solved
tceburashka at yandex dot ru ¶
7 years ago
Send body file use RFC7578 ("multipart/form-data")
// class contain file
class oFile
{
private $name;
private $mime;
private $content;
public function __construct($name, $mime=null, $content=null)
{
if(is_null($content))
{
$info = pathinfo($name);
// check is exist and readable file
if(!empty($info['basename']) && is_readable($name))
{
$this->name = $info['basename'];
// get MIME
$this->mime = mime_content_type($name);
// load file
$content = file_get_contents($name);
if($content!==false) $this->content = $content;
else throw new Exception('Don`t get content - "'.$name.'"');
} else throw new Exception('Error param');
} else
{
$this->name = $name;
if(is_null($mime)) $mime = mime_content_type($name);
$this->mime = $mime;
$this->content = $content;
};
}
public function Name() { return $this->name; }
public function Mime() { return $this->mime; }
public function Content() { return $this->content; }
};
// create body for POST request
class BodyPost
{
// part "multipart/form-data"
public static function PartPost($name, $val)
{
$body = 'Content-Disposition: form-data; name="' . $name . '"';
// check instance of oFile
if($val instanceof oFile)
{
$file = $val->Name();
$mime = $val->Mime();
$cont = $val->Content();
$body .= '; filename="' . $file . '"' . "rn";
$body .= 'Content-Type: ' . $mime ."rnrn";
$body .= $cont."rn";
} else $body .= "rnrn".urlencode($val)."rn";
return $body;
}
public static function Get(array $post, $delimiter='-------------0123456789')
{
if(is_array($post) && !empty($post))
{
$bool = false;
foreach($post as $val) if($val instanceof oFile) {$bool = true; break; };
if($bool)
{
$ret = '';
foreach($post as $name=>$val)
$ret .= '--' . $delimiter. "rn". self::PartPost($name, $val);
$ret .= "--" . $delimiter . "--rn";
} else $ret = http_build_query($post);
} else throw new Exception('Error input param!');
return $ret;
}
};
$delimiter = '-------------'.uniqid();
$file = new oFile('sample.txt', 'text/plain', 'Content file');
$post = BodyPost::Get(array('field'=>'text', 'file'=>$file), $delimiter);
var_dump($post);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://server/upload/');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data; boundary=' . $delimiter,
'Content-Length: ' . strlen($post)));
curl_exec($ch);
adrian at foeder dot de ¶
10 years ago
if you want to do a GET request with additional body data it will become tricky not to implicitly change the request to a POST, like many notes below correctly state.
So to do the analogy of command line's
curl -XGET 'http://example.org?foo=bar' -d '<baz>some additional data</baz>'
in PHP you'll do, besides your other necessary stuff,
<?php
curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, '<baz>some additional data</baz>');
?>
during my experiments, every other "similar" way, like e.g. CURLOPT_HTTPGET, didn't send the additional data or fell into POST.
ericbianchetti at gmail dot com ¶
13 years ago
if you need to send a SOAP string that is the CURL you must use :
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, XML_POST_URL);
curl_setopt ($ch, CURLOPT_HTTPHEADER, array('SOAPAction: ""'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, XML_PAYLOAD);
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
?>
Note : Having based my snipet on Chemo demonstration (oscommerce user know who he is), XML_POST_URL and XML_PAYLOAD where defined as constant with define().
The point is : at the opposite of .xml , SOAP must send the header 'SOAPAction: ""' that can be a valid URI, an empty string (that is here) or nothing ('SOAPAction: '). The later case baing not accepted by all server, the second one indicating the target is the URI used to post the SOAP.
http://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383528
Niki Romagnoli ¶
1 month ago
Set order when using CURLOPT_POST and CURLOPT_POSTFIELDS *matters*.
Setting CURL_POST to true will ERASE any previous CURLOPT_POSTFIELDS using an array. Result is request be a POST with empty body.
CURLOPT_POSTFIELDS will set CURLOPT_POST to true for you, no need for repeat.
If you really need to set both, then either:
- set CURLOPT_POST *before* CURLOPT_POSTFIELDS
- or don't use array and convert CURLOPT_POSTFIELDS to URL-encoded string, it will not be affected this way (ie. <?php curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($yourArray)); ?> )
reed at taeluf dot com ¶
3 months ago
setting `CURLOPT_USERPWD` to `user:password` is equivalent to `curl -u user:password`
simbiat at outlook dot com ¶
7 months ago
Apparently, when you use CURLOPT_FILE to direct output to a file instead of STDOUT after handle creation, it automatically sets CURLOPT_RETURNTRANSFER to false. If you try to reuse the handle in such a situation (even with a different file), you may get warning like "CURLOPT_FILE resource has gone away, resetting to default" and content of the previous response will be sent to browser (and seemingly exit the script). To avoid this behavior, you need to CURLOPT_RETURNTRANSFER to true after updating CURLOPT_FILE. If you do want the response from the handle as a string, that is.
urkle at outoforder dot cc ¶
14 years ago
To send a post as a different content-type (ie.. application/json or text/xml) add this setopt call
<?php
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
?>
julien veneziano ¶
13 years ago
If you need to send deta in a DELETE request, use:
<?php
$request_body = 'some data';
$ch = curl_init('http://www.example.com');
curl_setopt($ch, CURLOPT_POSTFIELDS, $request_body);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
$response = curl_exec($ch);
var_dump($response);
?>
nabikaz at gmail dot com ¶
6 years ago
About this post in here:
http://php.net/manual/en/function.curl-setopt.php#102121
>Handling redirections with curl if safe_mode or open_basedir is enabled.
>...
>function curl_exec_follow(/*resource*/ $ch, /*int*/ &$maxredirect = null) {
>...
~~~~~~~~~~~~~
IMPORTANT:
This is not work if set "CURLOPT_FILE".
For resolve this issue, can return $ch instead of curl_exec($ch), and after then set CURLOPT_FILE and use curl_exec($ch).
bash at noemailaddress dot com ¶
4 years ago
Be sure not to set CURLOPT_POST to 1 (or True) if you are uploading a file, even if you are also providing textual Post data in your request. Took two hours to discover that including this option was the cause of my receiving script not having $_FILES set. The documentation explains it, but many examples around the web incorrectly include the CURLOPT_POST option in their example code. (Their examples only work because they happen to set this option first, and curl automatically resets it if you set CURLOPT_POSTFIELDS and it includes a file. Set your post fields first and then the CURLOPT_POST option however, and your code will not work.)
Per the documentation:
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. "
mikko dot rantalainen at peda dot net ¶
7 years ago
If you need to do DELETE request, use CURLOPT_CUSTOMREQUEST with "DELETE" and use CURLOPT_POSTFIELDS for parameters. Do not put request parameters into the URL (GET-like) or bad things will happen (at least Apache+mod_php does not like such requests).
steve at websmithery dot co dot uk ¶
6 years ago
It may not be an issue which affects anyone, but I think it’s worth noting that using the CURLOPT_POSTFIELDS option has the side effect of setting the CURLOPT_POST option to TRUE.
When testing some code that required the post method, I commented out my CURLOPT_POST line to see how it failed and it didn't. Further investigation using curl_getinfo revealed that setting the CURLOPT_POSTFIELDS option was also setting the POST option.
Joan ¶
9 years ago
Using CURLOPT_NOPROXY to avoid using the proxy for some urls is very convenient.
For example when the page is trying to look for itself.
The parameter can be found at least in version 5.5.7, (probably earlier)
Unfortunately it's not present on debian wheezy (5.4.4) but it will be on jessie (it's already there)
A related bug: https://bugs.php.net/bug.php?id=53543
White Gandalf ¶
8 years ago
to complement shiplu's comment on the neccessary option sequence of CURLOPT_POST before CURLOPT_POSTFIELDS:
The crux is not some error on nginx, but that nothing at all will be send over the line by curl. Parameters set by a "CURLOPT_POSTFIELDS" option setting will be completely ignored, as long as no "CURLOPT_POST" has been encountered beforehand: Neigther the Content-Type header will be set/generated accordingly nor Content-Length nor any data will be send in the body.
When using curl_setopt_array, the sequence in the array matters as well.
S.F. ¶
10 years ago
I spent a couple of days trying to upload a file using a curl post.
The problem I ran into was the filename had an '@' in the middle of it. It turned out that at least on my system if I encoded the file path using the quoted_printable_encode() function the upload works.
I'm posting this in the hopes that it will help someone else, and for my own future reference.
Code:
<?php
$filepath
= '/tmp/test@example.txt';
$postdata['file'] = '@' . quoted_printable_encode($filepath);
//... supporting code.
$result = curl_exec($ch);
?>
I'm not exactly sure why this works when escaping the '@' doesn't work but it does for me.
If anyone can offer insight into why this works or a better way to handle the '@' symbol in a filename when using curl to upload I would love to hear it.
Thanks
ellert at _removeme_ vankoperen dot nl ¶
11 years ago
If you are using curl to do a soap request and consistently get the following error back:
The server cannot service the request because the media type is unsupported.
You are sending the Content-type of soap 1.2 to a 1.1 server.
Soap 1.1 needs Content-Type: text/xml;
Soap 1.2 should have Content-Type: application/soap+xml;
v dot tverdun at gmail dot com ¶
11 years ago
Make sure to set keys for array if passing to CURLOPT_POSTFIELDS.
<?php
//This can cause errors
$data = array('bar');//Use this instead
$data = array('foo' => 'bar');curl_setopt(CURLOPT_POSTFIELDS, $data);
?>
john dot david dot steele at gmail dot com ¶
12 years ago
A note on the way Curl posts files...
<?php
curl_setopt($ch, CURLOPT_POSTFIELDS, array('file' => '@/path/to/file.ext');
?>
will post the FULL PATH of the file in the filename field:
Content-Disposition: form-data; name="file"; filename="/path/to/file.ext"
Whereas typical browser behavior only sends the filename:
Content-Disposition: form-data; name="file"; filename="file.ext"
Workaround:
<?php
curl_setopt($ch, CURLOPT_POSTFIELDS, array('file' => '@file.ext');
$cwd = getcwd();
chdir('/path/to/');
$receivedData = curl_exec($ch);
chdir($cwd);
?>
kavih7 at yahoo dot com ¶
12 years ago
When POSTing with cURL, my POSTs were magically being converted to GETs and I debugged it until finding the issue. I was setting the CURLOPT_MUTE option. Not sure why this conflicts, since the documentation doesn't specify as such. Anyways, if your $_POST is empty, make sure you aren't setting CURLOPT_MUTE.
Cheers!
obones_remove_me at free dot fr ¶
13 years ago
For those of you wondering how to specify the content-type for a file uploaded via curl, the syntax is as follows:
<?php
$data
= array('file' => '@/home/user/test.png;type=image/png');?>
Simply adding a semicolon with the type= at the end.
Note that this has been reported not to work in all versions of PHP and I have done the following tests:
5.2.6 (libcurl 7.18.2) : Does not work
5.2.13 (libcurl 7.20.0) : Works just fine
So it might be worth updating your installation of PHP and/or libcurl if you want to be able to use this syntax
Andrew ¶
13 years ago
I noticed that if you want to get current cookie file after curl_exec() - you need to close current curl handle (like it said in manual), but if you want cookies to be dumped to file after any curl_exec (without curl_close) you can:
<?php
#call it normally
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/');
$result1 = curl_exec($ch);
#and then make a temp copy
$ch_temp=curl_copy_handle(ch);
curl_close($ch);
$ch=$ch_temp;
?>
Only this way, if you close $ch_temp - cookies wont be dumped.
jID ¶
14 years ago
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
andrabr at gmail dot com ¶
15 years ago
This is very clear in hindsight, but it still cost me several hours:
<?php 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...
heyrocker at yahoo dot com ¶
17 years ago
The examples below for HTTP file upload work great, but I wanted to be able to post multiple files through HTTP upload using HTML arrays as specified in example 38.3 at
http://php.net/features.file-upload
In this case, you need to set the arrays AND keys in the $post_data, it will not work with just the array names. The following example shows how this works:
<?php
$post_data
= array();
$post_data['pictures[0]'] = "@cat.jpg";
$post_data['pictures[1]'] = "@dog.jpg";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/my_url.php" );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$postResult = curl_exec($ch);
if (
curl_errno($ch)) {
print curl_error($ch);
}
curl_close($ch);
print "$postResult";
?>
ikendra at yken dot nospam dot org ¶
18 years ago
Using cURL, I needed to call a third-party script which was returning binary data as attachment to pass on retrieved data again as attachment.
Problem was that the third-party script occassionally returned HTTP errors and I wanted to avoid passing on zero-length attachment in such case.
Combination of using CURLOPT_FAILONERROR and CURLOPT_HEADERFUNCTION callback helped to process the third-party script HTTP errors neatly:
<?php
function curlHeaderCallback($resURL, $strHeader) {
if (preg_match('/^HTTP/i', $strHeader)) {
header($strHeader);
header('Content-Disposition: attachment; filename="file-name.zip"');
}
return strlen($strHeader);
}
$strURL = 'http://www.example.com/script-whichs-dumps-binary-attachment.php';
$resURL = curl_init();
curl_setopt($resURL, CURLOPT_URL, $strURL);
curl_setopt($resURL, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($resURL, CURLOPT_HEADERFUNCTION, 'curlHeaderCallback');
curl_setopt($resURL, CURLOPT_FAILONERROR, 1);
curl_exec ($resURL);
$intReturnCode = curl_getinfo($resURL, CURLINFO_HTTP_CODE);
curl_close ($resURL);
if (
$intReturnCode != 200) {
print 'was error: ' . $intReturnCode;
}
?>
miloshio at gmail dot com ¶
10 years ago
Remember:
- 'Server-side' cookies exists as information even before they were set on browser agent(HTTP COOKIE HEADER),
- javascript cookies does NOT exists as information before they were set on browser agent,
so, if you're trying to save cookies using CURLOPT_COOKIEJAR to a local file, that cookie must be server - side cookie, otherwise you are wasting time, javascript-produced cookies only exists when client browser's JS interpreter set them.
lachlan at radelaide dot net ¶
9 years ago
For those using CURLAUTH_NTLM, it may come to no surprise that NTLM request will fail if you have set CURLOPT_FORBID_REUSE to true.
This is because NTLM authorisation is connect-based, not request-based. If the connection is not kept alive and re-used, cURL can never complete the request.
You may notice this if you get a 401 status code or max out the number of redirects.
w dot danford at electronics-software dot com ¶
14 years ago
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.
ashooner — — gmail , com ¶
14 years ago
When passing CURLOPT_POSTFIELDS a url-encoded string in order to use Content-Type: application/x-www-form-urlencoded, you can pass a string directly:
<?php
curl_setopt(CURLOPT_POSTFIELDS, 'field1=value&field2=value2');
?>
rather than passing the string in an array, as in fred at themancan dot com's example.
prohfesor at gmail dot com ¶
12 years ago
This function helps to parse netscape cookie file, generated by cURL into cookie array:
<?php
function _curl_parse_cookiefile($file) {
$aCookies = array();
$aLines = file($file);
foreach($aLines as $line){
if('#'==$line{0})
continue;
$arr = explode("t", $line);
if(isset($arr[5]) && isset($arr[6]))
$aCookies[$arr[5]] = $arr[6];
}
return
$aCookies;
}
?>
Martin K. ¶
9 years ago
If you need to read page contents in between file downloads, while still using the same curl handle, you'll probably need this code:
<?php
curl_setopt($handle, CURLOPT_FILE, fopen('php://stdout','w')); // 'php://output' didn't work for me
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); // using CURLOPT_FILE sets this to false automatically
?>