curl_setopt

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

curl_setopt设置 cURL 传输选项

说明

curl_setopt(CurlHandle $handle, int $option, mixed $value): bool

为 cURL 会话句柄设置选项。

参数

handle

curl_init() 返回的 cURL 句柄。

option

需要设置的CURLOPT_XXX选项。

value

将设置在option选项上的值。

以下 option 参数的 value应该被设置成 bool 类型:

选项 value 设置为 备注
CURLOPT_AUTOREFERER true 时将根据 Location: 重定向时,自动设置 header 中的Referer:信息。
CURLOPT_COOKIESESSION 设为 true 时将开启新的一次 cookie 会话。它将强制 libcurl 忽略之前会话时存的其他 cookie。 libcurl 在默认状况下无论是否为会话,都会储存、加载所有 cookie。会话 cookie 是指没有过期时间,只存活在会话之中。
CURLOPT_CERTINFO true 将在安全传输时输出 SSL 证书信息到 STDERR 在 cURL 7.19.1 中添加。 需要开启 CURLOPT_VERBOSE 才有效。
CURLOPT_CONNECT_ONLY true 将让库执行所有需要的代理、验证、连接过程,但不传输数据。此选项用于 HTTP、SMTP 和 POP3。 在 7.15.2 中添加。
CURLOPT_CRLF 启用时将Unix的换行符转换成回车换行符。
CURLOPT_DNS_USE_GLOBAL_CACHE true 会启用一个全局的DNS缓存。此选项非线程安全的,默认已开启。
CURLOPT_FAILONERROR 当 HTTP 状态码大于等于 400,true 将将显示错误详情。 默认情况下将返回页面,忽略 HTTP 代码。
CURLOPT_SSL_FALSESTART true 开启 TLS False Start (一种 TLS 握手优化方式) cURL 7.42.0 中添加。自 PHP 7.0.7 起有效。
CURLOPT_FILETIME true 时,会尝试获取远程文档中的修改时间信息。 信息可通过curl_getinfo()函数的CURLINFO_FILETIME 选项获取。
CURLOPT_FOLLOWLOCATION true 时将会根据服务器返回 HTTP 头中的 "Location: " 重定向。参阅 CURLOPT_MAXREDIRS
CURLOPT_FORBID_REUSE true 在完成交互以后强制明确的断开连接,不能在连接池中重用。
CURLOPT_FRESH_CONNECT true 强制获取一个新的连接,而不是缓存中的连接。
CURLOPT_FTP_USE_EPRT true 时,当 FTP 下载时,使用 EPRT (和 LPRT)命令。 设置为 false 时禁用 EPRT 和 LPRT,仅仅使用PORT 命令。
CURLOPT_FTP_USE_EPSV true 时,在FTP传输过程中,回到 PASV 模式前,先尝试 EPSV 命令。设置为 false 时禁用 EPSV。
CURLOPT_FTP_CREATE_MISSING_DIRS true 时,当 ftp 操作不存在的目录时将创建它。
CURLOPT_FTPAPPEND true 为追加写入文件,而不是覆盖。
CURLOPT_TCP_NODELAY true 时禁用 TCP 的 Nagle 算法,就是减少网络上的小数据包数量。 编译的版本在 libcurl 7.11.2 及以上时有效。
CURLOPT_FTPASCII CURLOPT_TRANSFERTEXT 的别名。
CURLOPT_FTPLISTONLY true 时只列出 FTP 目录的名字。
CURLOPT_HEADER 启用时会将头文件的信息作为数据流输出。
CURLINFO_HEADER_OUT true 时追踪句柄的请求字符串。 CURLINFO_ 的前缀是指向的(intentional)。
CURLOPT_HTTP09_ALLOWED 是否允许 HTTP/0.9 响应。从 libcurl 7.66.0 开始默认为 false;以前默认为 true 如果编译的 libcurl 版本 >= 7.64.0,则分别从 PHP 7.3.15 和 7.4.3 开始可用
CURLOPT_HTTPGET true 时会设置 HTTP 的 method 为 GET,由于默认是 GET,所以只有 method 被修改时才需要这个选项。
CURLOPT_HTTPPROXYTUNNEL true 会通过指定的 HTTP 代理来传输。
CURLOPT_HTTP_CONTENT_DECODING false 时获取原始 HTTP 响应主体。 如果编译的 libcurl >= 7.16.2 时可用。
CURLOPT_KEEP_SENDING_ON_ERROR true 时,如果返回的 HTTP 代码等于或大于 300,则继续发送请求主体。默认操作是停止发送并关闭流或连接。适用于手动 NTLM 身份验证。大多数应用程序不需要此选项。 如果编译的 libcurl >= 7.51.0,则从 PHP 7.3.0 开始可用。
CURLOPT_MUTE true 时将完全静默,无论是何 cURL 函数。 在 cURL 7.15.5 中移出(可以使用 CURLOPT_RETURNTRANSFER 作为代替)
CURLOPT_NETRC true 时,在连接建立时,访问~/.netrc文件获取用户名和密码来连接远程站点。
CURLOPT_NOBODY true 时将不输出 BODY 部分。同时 Mehtod 变成了 HEAD。修改为 false 时不会变成 GET。
CURLOPT_NOPROGRESS

true 时关闭 cURL 的传输进度。

注意:

PHP 默认自动设置此选项为 true,只有为了调试才需要改变设置。

CURLOPT_NOSIGNAL true 时忽略所有的 cURL 传递给 PHP 进程的信号。在 SAPI 多线程传输时此项被默认启用,所以超时选项仍能使用。 cURL 7.10时被加入。
CURLOPT_PATH_AS_IS true 不处理 dot dot sequences (即 ../ ) cURL 7.42.0 时被加入。 PHP 7.0.7 起有效。
CURLOPT_PIPEWAIT true 则等待 pipelining/multiplexing。 cURL 7.43.0 时被加入。 PHP 7.0.7 起有效。
CURLOPT_POST true 时会发送 POST 请求,类型为:application/x-www-form-urlencoded,是 HTML 表单提交时最常见的一种。
CURLOPT_PUT true 时允许 HTTP 发送文件。要被 PUT 的文件必须在 CURLOPT_INFILECURLOPT_INFILESIZE 中设置。
CURLOPT_RETURNTRANSFER truecurl_exec()获取的信息以字符串返回,而不是直接输出。
CURLOPT_SASL_IR true 开启,收到首包(first packet)后发送初始的响应(initial response)。 cURL 7.31.10 中添加,自 PHP 7.0.7 起有效。
CURLOPT_SSL_ENABLE_ALPN false 禁用 SSL 握手中的 ALPN (如果 SSL 后端的 libcurl 内建支持) 用于协商到 http2。 cURL 7.36.0 中增加, PHP 7.0.7 起有效。
CURLOPT_SSL_ENABLE_NPN false 禁用 SSL 握手中的 NPN(如果 SSL 后端的 libcurl 内建支持),用于协商到 http2。 cURL 7.36.0 中增加, PHP 7.0.7 起有效。
CURLOPT_SSL_VERIFYPEER false 禁止 cURL 验证对等证书(peer's certificate)。要验证的交换证书可以在 CURLOPT_CAINFO 选项中设置,或在 CURLOPT_CAPATH中设置证书目录。 自cURL 7.10开始默认为 true。从 cURL 7.10开始默认绑定安装。
CURLOPT_SSL_VERIFYSTATUS true 验证证书状态。 cURL 7.41.0 中添加, PHP 7.0.7 起有效。
CURLOPT_PROXY_SSL_VERIFYPEER false 会阻止 CURL 验证对等证书(peer's certificate)。可以使用 CURLOPT_CAINFO 选项指定要验证的备用证书,或者可以使用 CURLOPT_CAPATH 选项指定证书目录。设置为 false 时,无论如何验证对等证书都会成功。 默认为 true。自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_SAFE_UPLOAD 始终为 true,在 CURLOPT_POSTFIELDS 中禁用了对上传文件的 @ 前缀的支持,这意味着以 @ 开头的值可以作为字段安全地传递。上传可使用 CURLFile 替代。
CURLOPT_TCP_FASTOPEN true 开启 TCP Fast Open。 cURL 7.49.0 中添加, PHP 7.0.7 起有效。
CURLOPT_TFTP_NO_OPTIONS true 不发送 TFTP 的 options 请求。 自 cURL 7.48.0 添加, PHP 7.0.7 起有效。
CURLOPT_TRANSFERTEXT true 对 FTP 传输使用 ASCII 模式。对于LDAP,它检索纯文本信息而非 HTML。在 Windows 系统上,系统不会把 STDOUT 设置成二进制 模式。
CURLOPT_UNRESTRICTED_AUTH true 在使用CURLOPT_FOLLOWLOCATION重定向 header 中的多个 location 时继续发送用户名和密码信息,哪怕主机名已改变。
CURLOPT_UPLOAD true 准备上传。
CURLOPT_VERBOSE true 会输出所有的信息,写入到STDERR,或在CURLOPT_STDERR中指定的文件。

以下 optionvalue 应该被设置成 int

选项 设置 value 备注
CURLOPT_BUFFERSIZE 每次读入的缓冲的尺寸。当然不保证每次都会完全填满这个尺寸。 在cURL 7.10中被加入。
CURLOPT_CONNECTTIMEOUT 在尝试连接时等待的秒数。设置为0,则无限等待。
CURLOPT_CONNECTTIMEOUT_MS 尝试连接等待的时间,以毫秒为单位。设置为0,则无限等待。 如果 libcurl 编译时使用系统标准的名称解析器( standard system name resolver),那部分的连接仍旧使用以秒计的超时解决方案,最小超时时间还是一秒钟。 在 cURL 7.16.2 中被加入。
CURLOPT_DNS_CACHE_TIMEOUT 设置在内存中缓存 DNS 的时间,默认为120秒(两分钟)。
CURLOPT_EXPECT_100_TIMEOUT_MS Expect: 100-continue 响应的超时时间,以毫秒为单位。 默认为 1000 毫秒。 cURL 7.36.0 中添加,自 PHP 7.0.7 有效。
CURLOPT_FTPSSLAUTH FTP验证方式(启用的时候):CURLFTPAUTH_SSL (首先尝试SSL),CURLFTPAUTH_TLS (首先尝试TLS)或CURLFTPAUTH_DEFAULT (让cURL 自个儿决定)。 在 cURL 7.12.2 中被加入。
CURLOPT_HEADEROPT

如何处理 header。以下常量中的某个:

CURLHEADER_UNIFIED
CURLOPT_HTTPHEADER 中指定的 header 将用于对服务器和代理的请求。启用此选项后,CURLOPT_PROXYHEADER 将不起作用。
CURLHEADER_SEPARATE
使 CURLOPT_HTTPHEADER header 仅发送到服务器而不发送到代理。代理 header 必须使用 CURLOPT_PROXYHEADER 进行设置才能使用。注意,如果将非 CONNECT 请求发送到代理,libcurl 将发送服务器 header 和代理 header。执行 CONNECT 时,libcurl 将仅将 CURLOPT_PROXYHEADER header 发送到代理,然后仅将 CURLOPT_HTTPHEADER header 发送到服务器。

从 cURL 7.42.1 起默认是 CURLHEADER_SEPARATE,之前默认是 CURLHEADER_UNIFIED
Added in cURL 7.37.0. Available since PHP 7.0.7.
CURLOPT_HTTP_VERSION CURL_HTTP_VERSION_NONE (默认值,让 cURL 自己判断使用哪个版本),CURL_HTTP_VERSION_1_0 (强制使用 HTTP/1.0)或CURL_HTTP_VERSION_1_1 (强制使用 HTTP/1.1)。
CURLOPT_HTTPAUTH

使用的 HTTP 验证方法。选项有: CURLAUTH_BASICCURLAUTH_DIGESTCURLAUTH_GSSNEGOTIATECURLAUTH_NTLMCURLAUTH_AWS_SIGV4CURLAUTH_ANYCURLAUTH_ANYSAFE

可以使用 | 位域(OR)操作符结合多个值,cURL 会让服务器选择受支持的方法,并选择最好的那个。

CURLAUTH_ANY 设置所有的位。cURL 将自动选择它认为最安全的一个。

CURLAUTH_ANYSAFE 设置了除 CURLAUTH_BASIC 以外所有的位。cURL 将自动选择它认为最安全的一个。

CURLOPT_INFILESIZE 希望传给远程站点的文件尺寸,字节(byte)为单位。 注意无法用这个选项阻止 libcurl 发送更多的数据,确切发送什么取决于 CURLOPT_READFUNCTION
CURLOPT_LOW_SPEED_LIMIT 传输速度,每秒字节(bytes)数,根据CURLOPT_LOW_SPEED_TIME秒数统计是否因太慢而取消传输。
CURLOPT_LOW_SPEED_TIME 当传输速度小于CURLOPT_LOW_SPEED_LIMIT时(bytes/sec),PHP会判断是否因太慢而取消传输。
CURLOPT_MAIL_RCPT_ALLLOWFAILS 允许一些收件人的 RCPT TO 命令失败。 在向多个收件人发送数据时,如果至少有一个收件人导致 RCPT TO 命令返回错误,默认情况下 cURL 将中止 SMTP 对话。此选项告诉 cURL 忽略错误并继续使用剩余的有效收件人。如果所有收件人触发 RCPT TO 失败并且设置了此 flag,cURL 将中止 SMTP 对话并返回从最后一个 RCPT TO 命令收到的错误。
CURLOPT_MAXAGE_CONN 重新使用已存在连接时允许的最大空闲时间。默认最大时间设置为 118 秒。
CURLOPT_MAXFILESIZE_LARGE The maximum file size in bytes allowed to download. If the file requested is found larger than this value, the transfer will not start and CURLE_FILESIZE_EXCEEDED will be returned. The file size is not always known prior to download, and for such files this option has no effect even if the file transfer ends up being larger than this given limit.
CURLOPT_MAXLIFETIME_CONN The maximum time in seconds, since the creation of the connection, that is allowed for an existing connection to have for it to be considered for reuse. If a connection is found in the cache that is older than this value, it will instead be closed once any in-progress transfers are complete. Default is 0 seconds, meaning the option is disabled and all connections are eligible for reuse.
CURLOPT_MAXCONNECTS 允许的最大持久连接数。当达到限制时,将会关闭缓存中最早的连接,以防止增加已打开的连接数。
CURLOPT_MAXREDIRS 指定最多的 HTTP 重定向次数,这个选项是和 CURLOPT_FOLLOWLOCATION 一起使用的。 默认值 20 是为了防止无限重定向。设置为 -1 允许无限重定向,0 拒绝所有重定向。
CURLOPT_PORT 用来指定连接端口。
CURLOPT_POSTREDIR 位掩码, 1 (301 永久重定向), 2 (302 Found) 和 4 (303 See Other) 设置 CURLOPT_FOLLOWLOCATION 时,什么情况下需要再次 HTTP POST 到重定向网址。 cURL 7.19.1 中添加。
CURLOPT_PROTOCOLS

CURLPROTO_*的位掩码。 启用时,会限制 libcurl 在传输过程中可使用哪些协议。 这将允许你在编译libcurl时支持众多协议,但是限制只用允许的子集。默认 libcurl 将使用所有支持的协议。 参见CURLOPT_REDIR_PROTOCOLS

可用的协议选项为: CURLPROTO_HTTPCURLPROTO_HTTPSCURLPROTO_FTPCURLPROTO_FTPSCURLPROTO_SCPCURLPROTO_SFTPCURLPROTO_TELNETCURLPROTO_LDAPCURLPROTO_LDAPSCURLPROTO_DICTCURLPROTO_FILECURLPROTO_TFTPCURLPROTO_MQTTCURLPROTO_ALL

在 cURL 7.19.4 中被加入。
CURLOPT_PROXYAUTH HTTP 代理连接的验证方式。使用在CURLOPT_HTTPAUTH中的位掩码。 当前仅仅支持 CURLAUTH_BASICCURLAUTH_NTLM 在 cURL 7.10.7 中被加入。
CURLOPT_PROXYPORT 代理服务器的端口。端口也可以在CURLOPT_PROXY中设置。
CURLOPT_PROXYTYPE 可以是 CURLPROXY_HTTP (默认值) CURLPROXY_SOCKS4CURLPROXY_SOCKS5CURLPROXY_SOCKS4ACURLPROXY_SOCKS5_HOSTNAME 在 cURL 7.10 中被加入。
CURLOPT_REDIR_PROTOCOLS CURLPROTO_* 值的位掩码。如果被启用,位掩码会限制 libcurl 在 CURLOPT_FOLLOWLOCATION开启时,使用的协议。 默认允许除 FILE 和 SCP 外所有协议。 这和 7.19.4 前的版本无条件支持所有支持的协议不同。关于协议常量,请参照CURLOPT_PROTOCOLS 在 cURL 7.19.4 中被加入。
CURLOPT_RESUME_FROM 在恢复传输时,传递字节为单位的偏移量(用来断点续传)。
CURLOPT_SOCKS5_AUTH

用于 SOCKS5 验证方法。选项是:CURLAUTH_BASICCURLAUTH_GSSAPICURLAUTH_NONE

位操作符 |(or)用于组合多个方法。如果这样做,cURL 将轮询服务器以查看它支持哪些方法并选择最佳方法。

CURLAUTH_BASIC 允许用户名/密码验证。

CURLAUTH_GSSAPI 允许 GSS-API 身份验证。

CURLAUTH_NONE 允许不验证。

默认为 CURLAUTH_BASIC|CURLAUTH_GSSAPI。使用 CURLOPT_PROXYUSERPWD 选项设置真实的用户名和密码。

从 7.3.0 和 curl >= 7.55.0 开始可用。
CURLOPT_SSL_OPTIONS

设置 SSL 行为选项,它是以下常量的位掩码:

CURLSSLOPT_ALLOW_BEAST
请勿尝试使用任何变通方法来弥补 SSL3 和 TLS1.0 协议中的安全漏洞。
CURLSSLOPT_NO_REVOKE
对存在此类行为的 SSL 后端禁用证书吊销检查。
CURLSSLOPT_AUTO_CLIENT_CERT
当服务器请求时,自动查找并使用客户端证书进行身份验证。此选项仅支持 Schannel(本机 Windows SSL 库)。
CURLSSLOPT_NATIVE_CA
使用操作系统的本地 CA 存储进行证书验证。仅在使用 OpenSSL 构建的 Windows 上有效。

注意: 此选项尚处于实验阶段,行为可能会发生变化。

CURLSSLOPT_NO_PARTIALCHAIN
不接受“partial”证书链,否则 cURL 默认会接受。此选项仅支持 OpenSSL,如果证书链以中间证书而不是根证书结尾,则证书验证将失败。
CURLSSLOPT_REVOKE_BEST_EFFORT
如果存在此类行为的 SSL 后端缺少分发点或分发点(distribution point)处于离线状态,则忽略证书吊销检查。此选项仅支持 Schannel(本机 Windows SSL 库)。

注意: 如果与 CURLSSLOPT_NO_REVOKE 结合使用,则后者优先。

自 cURL 7.25.0 添加,并且自 PHP 7.0.7 起可用。
CURLOPT_SSL_VERIFYHOST 2 时验证 SSL 对等证书中的公用名称字段或主题备用名称(Subject Alternate Name,简称 SNA)字段是否与提供的主机名匹配。0 时不检查名称。不应使用 1。在生产环境中,此选项的值应保持为 2(默认值)。 在 cURL 7.28.1 中移除了对 1 的支持。
CURLOPT_SSLVERSION

CURL_SSLVERSION_DEFAULT, CURL_SSLVERSION_TLSv1, CURL_SSLVERSION_SSLv2, CURL_SSLVERSION_SSLv3, CURL_SSLVERSION_TLSv1_0, CURL_SSLVERSION_TLSv1_1, CURL_SSLVERSION_TLSv1_2, CURL_SSLVERSION_TLSv1_3 中的其中一个。

可以使用 CURL_SSLVERSION_MAX_* 中的常量来设置最大 TLS 版本。

还可以将 CURL_SSLVERSION_* 中的某个常量与 CURL_SSLVERSION_MAX_* 的某个进行按位或运算。 CURL_SSLVERSION_MAX_DEFAULT(类库支持的最大版本), CURL_SSLVERSION_MAX_TLSv1_0, CURL_SSLVERSION_MAX_TLSv1_1, CURL_SSLVERSION_MAX_TLSv1_2, CURL_SSLVERSION_MAX_TLSv1_3

警告

最好不要设置此选项并使用默认值。因为考虑到 SSLv2 和 SSLv3 中已知的漏洞,将其设置为 CURL_SSLVERSION_SSLv2CURL_SSLVERSION_SSLv3 非常危险。

CURLOPT_PROXY_SSL_OPTIONS

设置代理 SSL 行为选项,它是以下常量的位掩码:

CURLSSLOPT_ALLOW_BEAST
不要尝试对 SSL3 和 TLS1.0 协议中的安全漏洞使用任何替代方法。
CURLSSLOPT_NO_REVOKE
对存在此类行为的 SSL 后端禁用证书吊销检查。(curl >= 7.44.0)
CURLSSLOPT_NO_PARTIALCHAIN
不接受“部分”(partial)证书链,不然默认接受。(curl >= 7.68.0)

自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY_SSL_VERIFYHOST 设置为 2 以根据代理名称验证 HTTPS 代理的证书名称字段。设置为 0 时,无论证书中使用的名称如何,连接都会成功。谨慎使用该能力! 在 curl 7.28.0 及更早版本中 1 视为调试选项。从 curl 7.28.1 到 7.65.3 返回 CURLE_BAD_FUNCTION_ARGUMENT。 从 curl 7.66.0 开始,12 被视为相同的值。在生产环境中,此选项的值应保持为 2(默认值)。 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY_SSLVERSION

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, CURL_SSLVERSION_SSLv3 中的一个。

警告

最好不要设置此选项并使用默认的 CURL_SSLVERSION_DEFAULT,这将尝试找出远程 SSL 协议版本。

自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_STREAM_WEIGHT 设置 stream weight 数值 ( 1 和 256 之间的数字). cURL 7.46.0 中添加,自 PHP 7.0.7 起有效。
CURLOPT_TCP_KEEPALIVE 如果设置为 1,将发送 TCP keepalive 探针。这些探针的延迟和频率可以通过 CURLOPT_TCP_KEEPIDLECURLOPT_TCP_KEEPINTVL 选项来控制,前提是操作系统支持它们。如果设置为 0(默认值),将禁用 keepalive 探针。 在 cURL 7.25.0 中添加。
CURLOPT_TCP_KEEPIDLE 设置延迟(以秒为单位),如果启用了 CURLOPT_TCP_KEEPALIVE,操作系统将在连接空闲时等待,然后再发送 keepalive 探针。并非所有操作系统都支持此选项。默认值为 60 在 cURL 7.25.0 中添加。
CURLOPT_TCP_KEEPINTVL 设置间隔(以秒为单位),如果启用了 CURLOPT_TCP_KEEPALIVE,操作系统将在发送 keepalive 探针之间等待。并非所有操作系统都支持此选项。默认值为 60 在 cURL 7.25.0 中添加。
CURLOPT_TIMECONDITION 设置如何对待 CURLOPT_TIMEVALUE。 使用 CURL_TIMECOND_IFMODSINCE,仅在页面 CURLOPT_TIMEVALUE 之后修改,才返回页面。没有修改则返回 "304 Not Modified" 头,假设设置了 CURLOPT_HEADERtrueCURL_TIMECOND_IFUNMODSINCE 则起相反的效果。使用 CURL_TIMECOND_NONE 忽略 CURLOPT_TIMEVALUE 并始终返回页面。默认为 CURL_TIMECOND_IFMODSINCE 在 cURL 7.46.0 之前,默认值为 CURL_TIMECOND_IFMODSINCE
CURLOPT_TIMEOUT 允许 cURL 函数执行的最长秒数。
CURLOPT_TIMEOUT_MS 设置cURL允许执行的最长毫秒数。 如果 libcurl 编译时使用系统标准的名称解析器( standard system name resolver),那部分的连接仍旧使用以秒计的超时解决方案,最小超时时间还是一秒钟。 在 cURL 7.16.2 中被加入。
CURLOPT_TIMEVALUE 秒数,从 1970年1月1日开始。这个时间将由 CURLOPT_TIMECONDITION 使用。
CURLOPT_UPKEEP_INTERVAL_MS Some protocols have "connection upkeep" mechanisms. These mechanisms usually send some traffic on existing connections in order to keep them alive. This option defines the connection upkeep interval. Currently, the only protocol with a connection upkeep mechanism is HTTP/2. When the connection upkeep interval is exceeded, an HTTP/2 PING frame is sent on the connection. Default is 60 seconds.
CURLOPT_UPLOAD_BUFFERSIZE Preferred buffer size in bytes for the cURL upload buffer. The upload buffer size by default is 64 kilobytes. The maximum buffer size allowed to be set is 2 megabytes. The minimum buffer size allowed to be set is 16 kilobytes.
CURLOPT_MAX_RECV_SPEED_LARGE 如果下载速度超过了此速度(以每秒字节数来统计) ,即传输过程中累计的平均数,传输就会降速到这个参数的值。默认不限速。 cURL 7.15.5 中添加。
CURLOPT_MAX_SEND_SPEED_LARGE 如果上传的速度超过了此速度(以每秒字节数来统计),即传输过程中累计的平均数 ,传输就会降速到这个参数的值。默认不限速。 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. cURL 7.16.1 中添加。
CURLOPT_IPRESOLVE 允许程序选择想要解析的 IP 地址类别。只有在地址有多种 ip 类别的时候才能用,可以的值有: CURL_IPRESOLVE_WHATEVERCURL_IPRESOLVE_V4CURL_IPRESOLVE_V6,默认是 CURL_IPRESOLVE_WHATEVER cURL 7.10.8 中添加。
CURLOPT_FTP_FILEMETHOD 告诉 curl 使用哪种方式来获取 FTP(s) 服务器上的文件。可能的值有: CURLFTPMETHOD_DEFAULTCURLFTPMETHOD_MULTICWDCURLFTPMETHOD_NOCWDCURLFTPMETHOD_SINGLECWD cURL 7.15.1 中添加。

对于下面的这些optionvalue应该被设置成 string

选项 设置的value 备注
CURLOPT_ALTSVC Pass the filename for cURL to use as the Alt-Svc cache file to read existing cache contents from and possibly also write it back to a after a transfer, unless CURLALTSVC_READONLYFILE is set via CURLOPT_ALTSVC_CTRL.
CURLOPT_ALTSVC_CTRL Populate the bitmask with the correct set of features to instruct cURL how to handle Alt-Svc for the transfers using this handle. cURL only accepts Alt-Svc headers over HTTPS. It will also only complete a request to an alternative origin if that origin is properly hosted over HTTPS. Setting any bit will enable the alt-svc engine. The options are: CURLALTSVC_H1, CURLALTSVC_H2, CURLALTSVC_H3, and CURLALTSVC_READONLYFILE.
CURLOPT_AWS_SIGV4

Provides AWS V4 signature authentication on HTTP(S) header.

This option overrides any other authentication types that have been set in CURLOPT_HTTPAUTH. This method cannot be combined with other authentication types.

CURLOPT_CAINFO 一个保存着1个或多个用来让服务端验证的证书的文件名。这个参数仅仅在和CURLOPT_SSL_VERIFYPEER一起使用时才有意义。 . 可能需要绝对路径。
CURLOPT_CAINFO_BLOB The name of a PEM file holding one or more certificates to verify the peer with. This option overrides CURLOPT_CAINFO. Available as of PHP 8.2.0 and cURL 7.77.0
CURLOPT_CAPATH 一个保存着多个CA证书的目录。这个选项是和CURLOPT_SSL_VERIFYPEER一起使用的。
CURLOPT_COOKIE 设定 HTTP 请求中"Cookie: "部分的内容。多个 cookie 用分号分隔,分号后带一个空格(例如, "fruit=apple; colour=red")。
CURLOPT_COOKIEFILE 包含 cookie 数据的文件名,cookie 文件的格式可以是 Netscape 格式,或者只是纯 HTTP 头部风格,存入文件。如果文件名是空的,不会加载 cookie,但 cookie 的处理仍旧启用。
CURLOPT_COOKIEJAR 当调用句柄的析构函数时,用于保存所有内部 cookie 的文件的名称。
警告

从 PHP 8.0.0 开始,curl_close() 为空操作(什么都不做),不会销毁句柄。如果需要在句柄自动销毁之前写入 cookie,请在句柄上调用 unset()

CURLOPT_COOKIELIST cookie 字符串(即 Netscape/Mozilla 的单行格式,或常规 HTTP 样式的 Set-Cookie 头)将单个 cookie 添加到内部 cookie 存储中。 "ALL" 擦除内存中保存的所有 cookie。 "SESS" 擦除内存中保存的所有会话 cookie。 "FLUSH" 将所有已知的 cookie 写入到 CURLOPT_COOKIEJAR 指定的文件。 "RELOAD"CURLOPT_COOKIEFILE 指定的文件中加载所有 cookie。 自 cURL 7.14.1 起可用。
CURLOPT_CUSTOMREQUEST

HTTP 请求时,使用自定义的 Method 来代替"GET""HEAD"。对 "DELETE" 或者其他更隐蔽的 HTTP 请求有用。 有效值如 "GET""POST""CONNECT"等等;也就是说,不要在这里输入整行 HTTP 请求。例如输入"GET /index.html HTTP/1.0\r\n\r\n"是不正确的。

注意:

不确定服务器支持这个自定义方法则不要使用它。

CURLOPT_DEFAULT_PROTOCOL

URL不带协议的时候,使用的默认协议。

cURL 7.45.0 中添加,自 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 类似CURLOPT_RANDOM_FILE,除了一个Entropy Gathering Daemon套接字。
CURLOPT_ENCODING HTTP请求头中"Accept-Encoding: "的值。 这使得能够解码响应的内容。 支持的编码有"identity""deflate""gzip"。如果为空字符串"",会发送所有支持的编码类型。 在 cURL 7.10 中被加入。
CURLOPT_FTPPORT 这个值将被用来获取供FTP"PORT"指令所需要的IP地址。 "PORT" 指令告诉远程服务器连接到我们指定的IP地址。这个字符串可以是纯文本的IP地址、主机名、一个网络接口名(UNIX下)或者只是一个'-'来使用默认的 IP 地址。
CURLOPT_HSTS

HSTS (HTTP Strict Transport Security) cache file name.

CURLOPT_HSTS_CTRL

Controls HSTS (HTTP Strict Transport Security) behavior. Populate the bitmask with the correct set of features to instruct cURL how to handle HSTS for the transfers using this handle. CURLHSTS_ENABLE enables the in-memory HSTS cache. If the HSTS cache file is defined, set CURLHSTS_READONLYFILE to make the file read-only.

CURLOPT_INTERFACE 发送的网络接口(interface),可以是一个接口名、IP 地址或者是一个主机名。
CURLOPT_KEYPASSWD 使用 CURLOPT_SSLKEYCURLOPT_SSH_PRIVATE_KEYFILE 私钥时候的密码。 在 cURL 7.16.1 中添加。
CURLOPT_KRB4LEVEL KRB4 (Kerberos 4) 安全级别。下面的任何值都是有效的(从低到高的顺序):"clear""safe""confidential""private".。如果字符串以上这些,将使用"private"。 这个选项设置为 null 时将禁用 KRB4 安全认证。目前 KRB4 安全认证只能用于 FTP 传输。
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 在 HTTP “POST”操作中要发送的所有数据。 这个参数可以是 urlencoded 后的字符串,类似'para1=val1&para2=val2&...',也可以使用一个以字段名为键值,字段数据为值的数组。 如果value是一个数组,Content-Type头将会被设置成multipart/form-data 可以使用 CURLFileCURLStringFile 发送文件,在这种情况下,value 必须是数组。
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 option CURLOPT_PROXYPORT. Defaults to using port 1080 for proxies if a port is not specified. 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY HTTP 代理通道。
CURLOPT_PROXY_SERVICE_NAME 代理验证服务的名称。 在 cURL 7.43.0 中添加了 HTTP 代理,在 cURL 7.49.0 中添加了 SOCKS5 代理。自 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. 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY_CAINFO_BLOB The name of a PEM 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 as of PHP 8.2.0 and libcurl >= cURL 7.77.0.
CURLOPT_PROXY_CAPATH The directory holding multiple CA certificates to verify the HTTPS proxy with. 自 PHP 7.3.0 和 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. 自 PHP 7.3.0 和 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. 自 PHP 7.3.0 和 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 ";" 自 PHP 7.3.0 和 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 with CURLOPT_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. 自 PHP 7.3.0 和 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". 自 PHP 7.3.0 和 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. 自 PHP 7.3.0 和 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 the CURLOPT_PROXY_SSL_CIPHER_LIST option. 自 PHP 7.3.0 和 libcurl >= cURL 7.61.0 起可用。使用 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. 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。如果启用内置 TLS,则可用。
CURLOPT_PROXY_SSLKEYTYPE The format of your private key. Supported formats are "PEM", "DER" and "ENG". 自 PHP 7.3.0 和 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. 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY_TLSAUTH_TYPE 用于 HTTPS 连接的 TLS 身份验证方法。支持的方法是 "SRP"

注意:

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.

自 PHP 7.3.0 和 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. 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXYUSERPWD 一个用来连接到代理的 "[username]:[password]" 格式的字符串。
CURLOPT_RANDOM_FILE 一个被用来生成 SSL 随机数种子的文件名。
CURLOPT_RANGE "X-Y"的形式,其中X和Y都是可选项获取数据的范围,以字节计。HTTP传输线程也支持几个这样的重复项中间用逗号分隔如"X-Y,N-M"
CURLOPT_REFERER 在HTTP请求头中"Referer: "的内容。
CURLOPT_SASL_AUTHZID The authorization identity (authzid) for the transfer. Only applicable to the PLAIN SASL authentication mechanism where it is optional. When not specified, only the authentication identity (authcid) as specified by the username will be sent to the server, along with the password. The server will derive the authzid from the authcid when not provided, which it will then use internally.
CURLOPT_SERVICE_NAME 验证服务的名称 cURL 7.43.0 起添加,自 PHP 7.0.7 有效。
CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 包含 32 位长的 16 进制数值。这个字符串应该是远程主机公钥(public key) 的 MD5 校验值。在不匹配的时候 libcurl 会拒绝连接。 此选项仅用于 SCP 和 SFTP 的传输。 cURL 7.17.1 中添加。
CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256 Base64-encoded SHA256 hash of the remote host's public key. The transfer will fail if the given hash does not match the hash the remote host provides.
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 一个SSL的加密算法列表。例如RC4-SHATLSv1都是可用的加密列表。
CURLOPT_SSL_EC_CURVES A colon delimited list of elliptic curve algorithms. For example, X25519:P-521 is a valid list of two elliptic curves. This option defines the client's key exchange algorithms in the SSL handshake, if the SSL backend cURL is built to use supports it.
CURLOPT_SSLCERT 一个包含 PEM 格式证书的文件名。
CURLOPT_SSLCERTPASSWD 使用CURLOPT_SSLCERT证书需要的密码。
CURLOPT_SSLCERTTYPE 证书的类型。支持的格式有"PEM" (默认值), "DER""ENG" 在 cURL 7.9.3中 被加入。
CURLOPT_SSLENGINE 用来在CURLOPT_SSLKEY中指定的SSL私钥的加密引擎变量。
CURLOPT_SSLENGINE_DEFAULT 用来做非对称加密操作的变量。
CURLOPT_SSLKEY 包含 SSL 私钥的文件名。
CURLOPT_SSLKEYPASSWD

CURLOPT_SSLKEY中指定了的SSL私钥的密码。

注意:

由于这个选项包含了敏感的密码信息,记得保证这个PHP脚本的安全。

CURLOPT_SSLKEYTYPE CURLOPT_SSLKEY中规定的私钥的加密类型,支持的密钥类型为"PEM"(默认值)、"DER""ENG"
CURLOPT_TLS13_CIPHERS 用于 TLS 1.3 连接的加密套件列表。列表必须在语法上正确,它由一个或多个用冒号分隔的加密套件字符串组成。当前仅当 curl 编译为使用 OpenSSL 1.1.1 或更高版本时才使用此选项。如果使用不同的 SSL 后端,CURLOPT_SSL_CIPHER_LIST 选项设置 TLS 1.3 加密套件。 自 PHP 7.3.0 和 libcurl >= cURL 7.61.0 起可用。使用 OpenSSL >= 1.1.1 编译时可用。
CURLOPT_UNIX_SOCKET_PATH 使用 Unix 套接字作为连接,并用指定的 string 作为路径。 cURL 7.40.0 中添加, PHP 7.0.7 起有效。
CURLOPT_URL 需要获取的 URL 地址,也可以在curl_init() 初始化会话的时候。
CURLOPT_USERAGENT 在HTTP请求中包含一个"User-Agent: "头的字符串。
CURLOPT_USERNAME 用于身份验证的用户名。 cURL 7.19.1 中添加。
CURLOPT_PASSWORD 用于身份验证的密码。 cURL 7.19.1 中添加。
CURLOPT_USERPWD 传递一个连接中需要的用户名和密码,格式为:"[username]:[password]"
CURLOPT_XOAUTH2_BEARER 指定 OAuth 2.0 access token。 cURL 7.33.0 中添加,自 PHP 7.0.7 添加。

以下optionvalue应该被设置成数组:

选项 可选value 备注
CURLOPT_CONNECT_TO 连接到指定的主机和端口,替换 URL 中的主机和端口。接受指定字符串格式的数组: HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT cURL 7.49.0 中添加, PHP 7.0.7 起有效。
CURLOPT_HTTP200ALIASES HTTP 200 响应码数组,数组中的响应码被认为是正确的响应,而非错误。 在 cURL 7.10.3 中被加入。
CURLOPT_HTTPHEADER 设置 HTTP 头字段的数组。格式: array('Content-type: text/plain', 'Content-length: 100')
CURLOPT_POSTQUOTE 在 FTP 请求执行完成后,在服务器上执行的一组array格式的 FTP 命令。
CURLOPT_PROXYHEADER 传给代理的自定义 HTTP 头。 cURL 7.37.0 中添加,自 PHP 7.0.7 添加。
CURLOPT_QUOTE 一组先于 FTP 请求的在服务器上执行的FTP命令。
CURLOPT_RESOLVE 提供自定义地址,指定了主机和端口。 包含主机、端口和 ip 地址的字符串,组成 array 的,每个元素以冒号分隔。格式: array("example.com:80:127.0.0.1") 在 cURL 7.21.3 中添加。

以下 optionvalue应该被设置成流资源 (例如使用fopen()):

选项 可选value
CURLOPT_FILE 设置输出文件,默认为STDOUT (浏览器)。
CURLOPT_INFILE 上传文件时需要读取的文件。
CURLOPT_STDERR 错误输出的地址,取代默认的STDERR
CURLOPT_WRITEHEADER 设置 header 部分内容的写入的文件地址。

以下optionvalue应该是有效的函数或者闭包:

选项 设置 value 笔记
CURLOPT_HEADERFUNCTION 设置一个回调函数,这个函数有两个参数,第一个是cURL的资源句柄,第二个是输出的 header 数据。header数据的输出必须依赖这个函数,返回已写入的数据大小。  
CURLOPT_PASSWDFUNCTION 设置一个回调函数,有三个参数,第一个是cURL的资源句柄,第二个是一个密码提示符,第三个参数是密码长度允许的最大值。返回密码的值。 从 PHP 7.3.0 开始移除。
CURLOPT_PROGRESSFUNCTION

设置一个回调函数,有五个参数,第一个是cURL的资源句柄,第二个是预计要下载的总字节(bytes)数。第三个是目前下载的字节数,第四个是预计传输中总上传字节数,第五个是目前上传的字节数。

注意:

只有设置 CURLOPT_NOPROGRESS 选项为 false 时才会调用这个回调函数。

返回非零值将中断传输。 传输将设置 CURLE_ABORTED_BY_CALLBACK 错误。

 
CURLOPT_READFUNCTION 回调函数名。该函数应接受三个参数。第一个是 cURL resource;第二个是通过选项 CURLOPT_INFILE 传给 cURL 的 stream resource;第三个参数是最大可以读取的数据的数量。回 调函数必须返回一个字符串,长度小于或等于请求的数据量(第三个参数)。一般从传入的 stream resource 读取。返回空字符串作为 EOF(文件结束) 信号。  
CURLOPT_WRITEFUNCTION 回调函数名。该函数应接受两个参数。第一个是 cURL resource;第二个是要写入的数据字符串。数 据必须在函数中被保存。 函数必须准确返回写入数据的字节数,否则传输会被一个错误所中 断。  
CURLOPT_XFERINFOFUNCTION 接受两个参数的回调。与 CURLOPT_PROGRESSFUNCTION 具有相似的目的,但更现代并且是 cURL 的首选选项。 在 7.32.0 中添加。 从 PHP 8.2.0 开始可用。

其他值:

Option 设置 value
CURLOPT_SHARE curl_share_init() 返回的结果。 使 cURL 可以处理共享句柄里的数据。

返回值

成功时返回 true, 或者在失败时返回 false

更新日志

版本 说明
8.0.0 handle 现在接受 CurlHandle 实例;之前接受 resource
7.3.15、7.4.3 引入 CURLOPT_HTTP09_ALLOWED
7.3.0 引入 CURLOPT_ABSTRACT_UNIX_SOCKETCURLOPT_KEEP_SENDING_ON_ERRORCURLOPT_PRE_PROXYCURLOPT_PROXY_CAINFOCURLOPT_PROXY_CAPATHCURLOPT_PROXY_CRLFILECURLOPT_PROXY_KEYPASSWDCURLOPT_PROXY_PINNEDPUBLICKEYCURLOPT_PROXY_SSLCERTCURLOPT_PROXY_SSLCERTTYPECURLOPT_PROXY_SSL_CIPHER_LISTCURLOPT_PROXY_SSLKEYCURLOPT_PROXY_SSLKEYTYPECURLOPT_PROXY_SSL_OPTIONSCURLOPT_PROXY_SSL_VERIFYHOSTCURLOPT_PROXY_SSL_VERIFYPEERCURLOPT_PROXY_SSLVERSIONCURLOPT_PROXY_TLSAUTH_PASSWORDCURLOPT_PROXY_TLSAUTH_TYPECURLOPT_PROXY_TLSAUTH_USERNAMECURLOPT_SOCKS5_AUTHCURLOPT_SUPPRESS_CONNECT_HEADERSCURLOPT_DISALLOW_USERNAME_IN_URLCURLOPT_DNS_SHUFFLE_ADDRESSESCURLOPT_HAPPY_EYEBALLS_TIMEOUT_MSCURLOPT_HAPROXYPROTOCOLCURLOPT_PROXY_TLS13_CIPHERSCURLOPT_SSH_COMPRESSIONCURLOPT_TIMEVALUE_LARGECURLOPT_TLS13_CIPHERS
7.0.7 引入 CURL_HTTP_VERSION_2CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGECURL_HTTP_VERSION_2TLSCURL_REDIR_POST_301CURL_REDIR_POST_302CURL_REDIR_POST_303CURL_REDIR_POST_ALLCURL_VERSION_KERBEROS5CURL_VERSION_PSLCURL_VERSION_UNIX_SOCKETSCURLAUTH_NEGOTIATECURLAUTH_NTLM_WBCURLFTP_CREATE_DIRCURLFTP_CREATE_DIR_NONECURLFTP_CREATE_DIR_RETRYCURLHEADER_SEPARATECURLHEADER_UNIFIEDCURLMOPT_CHUNK_LENGTH_PENALTY_SIZECURLMOPT_CONTENT_LENGTH_PENALTY_SIZECURLMOPT_MAX_HOST_CONNECTIONSCURLMOPT_MAX_PIPELINE_LENGTHCURLMOPT_MAX_TOTAL_CONNECTIONSCURLOPT_CONNECT_TOCURLOPT_DEFAULT_PROTOCOLCURLOPT_DNS_INTERFACECURLOPT_DNS_LOCAL_IP4CURLOPT_DNS_LOCAL_IP6CURLOPT_EXPECT_100_TIMEOUT_MSCURLOPT_HEADEROPTCURLOPT_LOGIN_OPTIONSCURLOPT_PATH_AS_ISCURLOPT_PINNEDPUBLICKEYCURLOPT_PIPEWAITCURLOPT_PROXY_SERVICE_NAMECURLOPT_PROXYHEADERCURLOPT_SASL_IRCURLOPT_SERVICE_NAMECURLOPT_SSL_ENABLE_ALPNCURLOPT_SSL_ENABLE_NPNCURLOPT_SSL_FALSESTARTCURLOPT_SSL_VERIFYSTATUSCURLOPT_STREAM_WEIGHTCURLOPT_TCP_FASTOPENCURLOPT_TFTP_NO_OPTIONSCURLOPT_UNIX_SOCKET_PATHCURLOPT_XOAUTH2_BEARERCURLPROTO_SMBCURLPROTO_SMBSCURLPROXY_HTTP_1_0CURLSSH_AUTH_AGENTCURLSSLOPT_NO_REVOKE

示例

示例 #1 初始化一个新的cURL会话并获取一个网页

<?php
// 创建一个新cURL资源
$ch = curl_init();

// 设置URL和相应的选项
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);

// 抓取URL并把它传递给浏览器
curl_exec($ch);

//关闭cURL资源,并且释放系统资源
curl_close($ch);
?>

注释

注意:

传递一个数组到CURLOPT_POSTFIELDS,cURL会把数据编码成 multipart/form-data,而然传递一个URL-encoded字符串时,数据会被编码成 application/x-www-form-urlencoded

参见

add a note

User Contributed Notes 64 notes

up
223
rmckay at webaware dot com dot au
11 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:\php\cacert.pem

Turning off CURLOPT_SSL_VERIFYPEER allows man in the middle (MITM) attacks, which you don't want!
up
49
joey
8 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 */
up
13
ashw1 - at - no spam - post - dot - cz
17 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);
}

?>
up
32
Steve Kamerman
13 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_error\n";
} else {
echo
"Data received: $data\n";
}
} else {
// Server
sleep(10);
echo
"Done.";
}
?>
up
3
qwertz182
3 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:\wamp64\tmp\php3016.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.
up
30
Philippe dot Jausions at 11abacus dot com
18 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
up
14
JScott jscott401 at gmail dot com
14 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 method

private 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
up
3
cmatiasvillanueva at gmail dot com
6 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");
up
27
sgamon at yahoo dot com
16 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/
up
6
mw+php dot net at lw-systems dot de
12 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:"));
up
37
Ed Cradock
14 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.
up
6
Victor Jerlin
15 years ago
Seems like some options not mentioned on this page, but listed on http://curl.haxx.se/libcurl/c/curl_easy_setopt.html is actually supported.

I was happy to see that I could actually use CURLOPT_FTP_CREATE_MISSING_DIRS even from PHP.
up
14
dweingart at pobox dot com
21 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
up
15
yann dot corno at free dot fr
21 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
up
16
luca dot manzo at bbsitalia dot com
18 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
up
17
Chris at PureFormSolutions dot com
15 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.
up
14
joelhy
8 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.
up
14
badman
10 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;
}
up
32
jade dot skaggs at gmail dot com
16 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);
}

?>
up
8
jancister at gmail dot com
9 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
}
?>
up
22
joeterranova at gmail dot com
14 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);
?>
up
5
skyogre __at__ yandex __dot__ ru
18 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) );

?>
up
9
fnjordy at gmail dot com
15 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.
up
3
juozaspo at gmail dot com
12 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.
up
3
Joey Hewitt
12 years ago
Note that if you put a certificate chain in a PEM file, the certificates need to be ordered so that each certificate is followed by its issuer (i.e., root last.)

Source: http://publib.boulder.ibm.com/tividd/td/ITIM/SC32-1493-00/en_US/HTML/im451_config09.htm
up
8
anderseta at gmail dot com
14 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.
up
11
PHP at RHaworth dot net
13 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.
up
7
Dustin Hawkins
18 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.
up
14
saidk at phirebranding dot com
15 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!
up
5
Martin K.
10 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.
up
12
Ojas Ojasvi
17 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
up
7
Aaron Wells
9 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.
up
11
mr at coder dot tv
18 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
up
2
eric dot van dot eldik at peercode dot nl
5 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");
?>
up
8
S\
13 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.
up
3
clint at fewbar dot com
14 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);

?>
up
5
ohcc at 163 dot com
6 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:\Web\www\wuxiancheng.cn\hello.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;
?>
up
7
Pawel Antczak
14 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("\r\n\r\n", $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("\r\n\r\n", $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.
up
10
regan dot corey at gmail dot com
11 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.
up
8
zsalab
13 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);
}
?>
up
9
Adam Monsen
12 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.
up
8
c00lways at gmail dot com
16 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 ;)
up
5
fred at themancan dot com
16 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.
up
4
scy-phpmanual at scytale dot name
13 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.
up
6
rob
15 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.
up
4
markandrewslade at gmail dot com
7 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.
up
4
ron at ttvavanti dot nl
20 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).
up
4
eion at bigfoot dot com
17 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("\n\n", $data, 2);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (
$http_code == 301 || $http_code == 302)
{
$matches = array();
preg_match('/Location:(.*?)\n/', $header, $matches);
$url = @parse_url(trim(array_pop($matches)));
if (!
$url)
{
//couldn't process the url to redirect to
$curl_loops = 0;
return
$data;
}
$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
if (!
$url['scheme'])
$url['scheme'] = $last_url['scheme'];
if (!
$url['host'])
$url['host'] = $last_url['host'];
if (!
$url['path'])
$url['path'] = $last_url['path'];
$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
curl_setopt($ch, CURLOPT_URL, $new_url);
debug('Redirecting to', $new_url);
return
curl_redir_exec($ch);
} else {
$curl_loops=0;
return
$data;
}
}
?>
up
3
anonymous
12 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.
up
2
michaeledwards.com
19 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);
?>
up
1
php at miggy dot org
18 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.
up
1
joel at mojamail dot com
6 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!
up
2
Salil Kothadia
16 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);
?>
up
3
qeremy [atta] gmail [dotta] com
12 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
up
1
gskluzacek at gmail dot com
13 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.
up
1
Andrew
15 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.
up
2
shiplu at programmer dot net
11 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);
?>
up
3
ac at an dot y-co dot de
16 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
up
2
Madcat
11 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("\0%s", '@text_to_upload')
);
?>

Original source: http://bit.ly/AntMle
up
1
Sylvain R
15 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');

?>
up
2
julien veneziano
14 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);
?>
up
1
adrian at foeder dot de
12 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.
up
2
Niki Romagnoli
1 year 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)); ?> )
up
1
alexchexes at gmail dot com
1 year ago
If you want cURL to successfully write cookies to a file specified with CURLOPT_COOKIEJAR, ensure that cURL has the necessary permissions to modify the file if it already exists.

I spent nearly a day trying to understand why cURL wasn't saving cookies to an existing file, even though I could easily modify the exact same file using file_put_contents(). Moreover, cURL itself could create the same file and save cookies, but only if it didn't previously exist.

Ultimately, the issue was related to file ownership. I was working within WSL2, inside a symlinked Windows directory. The [automount]"metadata" in wsl.conf was not set, causing every file created from PHP to have the default owner, which differed from the user running PHP.

Once I configured wsl.conf and then changed the ownership of the entire directory to match the user running PHP, cookies were successfully written to any file without any issues.
To Top