curl_setopt() - 设置 cURL 传输选项 - curl函数库
curl_setopt()
(PHP 4 >= 4.0.2, PHP 5, PHP 7)
设置 cURL 传输选项
说明
curl_setopt(resource $ch,int $option, mixed $value): bool为 cURL 会话句柄设置选项。
参数
$ch由curl_init()返回的 cURL 句柄。
$option需要设置的CURLOPT_XXX选项。
$value将设置在$option选项上的值。
以下$option参数的$value应该被设置成bool类型:
选项 | 将$value设置为 | 备注 |
---|---|---|
CURLOPT_AUTOREFERER | TRUE 时将根据Location:重定向时,自动设置 header 中的Referer:信息。 | |
CURLOPT_BINARYTRANSFER | 设为TRUE ,将在启用CURLOPT_RETURNTRANSFER 时,返回原生的(Raw)输出。 | 从 PHP 5.1.3 开始,此选项不再有效果:使用CURLOPT_RETURNTRANSFER 后总是会返回原生的(Raw)内容。 |
CURLOPT_COOKIESESSION | 设为TRUE 时将开启新的一次 cookie 会话。它将强制 libcurl 忽略之前会话时存的其他 cookie。 libcurl 在默认状况下无论是否为会话,都会储存、加载所有 cookie。会话 cookie 是指没有过期时间,只存活在会话之中。 | |
CURLOPT_CERTINFO | TRUE 将在安全传输时输出 SSL 证书信息到STDERR。 | 在 cURL 7.19.1 中添加。 PHP 5.3.2 后有效。需要开启CURLOPT_VERBOSE 才有效。 |
CURLOPT_CONNECT_ONLY | TRUE 将让库执行所有需要的代理、验证、连接过程,但不传输数据。此选项用于 HTTP、SMTP 和 POP3。 | 在 7.15.2 中添加。 PHP 5.5.0 起有效。 |
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:"重定向。(注意:这是递归的,"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 算法,就是减少网络上的小包数量。 | PHP 5.2.1 有效,编译时需要 libcurl 7.11.2 及以上。 |
CURLOPT_FTPASCII | CURLOPT_TRANSFERTEXT 的别名。 | |
CURLOPT_FTPLISTONLY | TRUE 时只列出 FTP 目录的名字。 | |
CURLOPT_HEADER | 启用时会将头文件的信息作为数据流输出。 | |
CURLINFO_HEADER_OUT | TRUE 时追踪句柄的请求字符串。 | 从 PHP 5.1.3 开始可用。CURLINFO_ 的前缀是有意的(intentional)。 |
CURLOPT_HTTPGET | TRUE 时会设置 HTTP 的 method 为 GET,由于默认是 GET,所以只有 method 被修改时才需要这个选项。 | |
CURLOPT_HTTPPROXYTUNNEL | TRUE 会通过指定的 HTTP 代理来传输。 | |
CURLOPT_MUTE | TRUE 时将完全静默,无论是何 cURL 函数。 | 在 cURL 7.15.5 中移出(可以使用 CURLOPT_RETURNTRANSFER 作为代替) |
CURLOPT_NETRC | TRUE 时,在连接建立时,访问~/.netrc文件获取用户名和密码来连接远程站点。 | |
CURLOPT_NOBODY | TRUE 时将不输出 BODY 部分。同时 Mehtod 变成了 HEAD。修改为FALSE 时不会变成 GET。 | |
CURLOPT_NOPROGRESS |
PHP 默认自动设置此选项为 | |
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_INFILE 和CURLOPT_INFILESIZE 中设置。 | |
CURLOPT_RETURNTRANSFER | TRUE 将curl_exec()获取的信息以字符串返回,而不是直接输出。 | |
CURLOPT_SAFE_UPLOAD | TRUE 禁用@前缀在CURLOPT_POSTFIELDS 中发送文件。意味着@可以在字段中安全得使用了。可使用CURLFile作为上传的代替。 | PHP 5.5.0 中添加,默认值FALSE 。 PHP 5.6.0 改默认值为TRUE 。. PHP 7 删除了此选项,必须使用 CURLFile interface 来上传文件。 |
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_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 中指定的文件。 |
以下$option的$value应该被设置成integer:
选项 | 设置$value为 | 备注 |
---|---|---|
CURLOPT_BUFFERSIZE | 每次读入的缓冲的尺寸。当然不保证每次都会完全填满这个尺寸。 | 在cURL 7.10中被加入。 |
CURLOPT_CLOSEPOLICY | CURLCLOSEPOLICY_* 中的一个。Note:此选项已被废弃,它不会被实现,永远不会有效果啦。 | PHP 5.6.0 中移除。 |
CURLOPT_CONNECTTIMEOUT | 在尝试连接时等待的秒数。设置为0,则无限等待。 | |
CURLOPT_CONNECTTIMEOUT_MS | 尝试连接等待的时间,以毫秒为单位。设置为0,则无限等待。如果 libcurl 编译时使用系统标准的名称解析器( standard system name resolver),那部分的连接仍旧使用以秒计的超时解决方案,最小超时时间还是一秒钟。 | 在 cURL 7.16.2 中被加入。从 PHP 5.2.3 开始可用。 |
CURLOPT_DNS_CACHE_TIMEOUT | 设置在内存中缓存 DNS 的时间,默认为120秒(两分钟)。 | |
CURLOPT_EXPECT_100_TIMEOUT_MS | 超时预计: 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 | 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 send CURLOPT_PROXYHEADER headers only to the proxy and then CURLOPT_HTTPHEADER headers only to the server. Defaults to CURLHEADER_SEPARATE as of cURL 7.42.1, and CURLHEADER_UNIFIED before. | 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_BASIC、$CURLAUTH_DIGEST、$CURLAUTH_GSSNEGOTIATE、$CURLAUTH_NTLM、$CURLAUTH_ANY和$CURLAUTH_ANYSAFE。 可以使用|位域(OR)操作符结合多个值,cURL 会让服务器选择受支持的方法,并选择最好的那个。 $CURLAUTH_ANY是CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM的别名。 $CURLAUTH_ANYSAFE是CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM的别名。 | |
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_MAXCONNECTS | 允许的最大连接数量。达到限制时,会通过CURLOPT_CLOSEPOLICY 决定应该关闭哪些连接。 | |
CURLOPT_MAXREDIRS | 指定最多的 HTTP 重定向次数,这个选项是和CURLOPT_FOLLOWLOCATION 一起使用的。 | |
CURLOPT_PORT | 用来指定连接端口。 | |
CURLOPT_POSTREDIR | 位掩码, 1(301 永久重定向), 2(302 Found)和 4(303 See Other)设置CURLOPT_FOLLOWLOCATION 时,什么情况下需要再次 HTTP POST 到重定向网址。 | cURL 7.19.1 中添加,PHP 5.3.2 开始可用。 |
CURLOPT_PROTOCOLS |
可用的协议选项为:$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。 | 在 cURL 7.19.4 中被加入。 |
CURLOPT_PROXYAUTH | HTTP 代理连接的验证方式。使用在CURLOPT_HTTPAUTH 中的位掩码。当前仅仅支持$CURLAUTH_BASIC和$CURLAUTH_NTLM。 | 在 cURL 7.10.7 中被加入。 |
CURLOPT_PROXYPORT | 代理服务器的端口。端口也可以在CURLOPT_PROXY 中设置。 | |
CURLOPT_PROXYTYPE | 可以是CURLPROXY_HTTP (默认值)CURLPROXY_SOCKS4 、CURLPROXY_SOCKS5 、CURLPROXY_SOCKS4A 或CURLPROXY_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_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 | 设置为1是检查服务器SSL证书中是否存在一个公用名(common name)。译者注:公用名(Common Name)一般来讲就是填写你将要申请SSL证书的域名(domain)或子域名(sub domain)。设置成 2,会检查公用名是否存在,并且是否与提供的主机名匹配。0为不检查名称。在生产环境中,这个值应该是2(默认值)。 | 值1的支持在 cURL 7.28.1 中被删除了。 |
CURLOPT_SSLVERSION | 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)中的其中一个。Note:你最好别设置这个值,让它使用默认值。设置为 2 或 3 比较危险,在 SSLv2 和 SSLv3 中有弱点存在。 | |
CURLOPT_STREAM_WEIGHT | 设置 stream weight 数值(1 和 256 之间的数字). | cURL 7.46.0 中添加,自 PHP 7.0.7 起有效。 |
CURLOPT_TIMECONDITION | 设置如何对待CURLOPT_TIMEVALUE 。使用$CURL_TIMECOND_IFMODSINCE,仅在页面CURLOPT_TIMEVALUE 之后修改,才返回页面。没有修改则返回"304 Not Modified"头,假设设置了CURLOPT_HEADER 为TRUE 。$CURL_TIMECOND_IFUNMODSINCE则起相反的效果。默认为$CURL_TIMECOND_IFMODSINCE。 | |
CURLOPT_TIMEOUT | 允许 cURL 函数执行的最长秒数。 | |
CURLOPT_TIMEOUT_MS | 设置cURL允许执行的最长毫秒数。如果 libcurl 编译时使用系统标准的名称解析器( standard system name resolver),那部分的连接仍旧使用以秒计的超时解决方案,最小超时时间还是一秒钟。 | 在 cURL 7.16.2 中被加入。从 PHP 5.2.3 起可使用。 |
CURLOPT_TIMEVALUE | 秒数,从 1970年1月1日开始。这个时间会被CURLOPT_TIMECONDITION 使。默认使用$CURL_TIMECOND_IFMODSINCE。 | |
CURLOPT_MAX_RECV_SPEED_LARGE | 如果下载速度超过了此速度(以每秒字节数来统计),即传输过程中累计的平均数,传输就会降速到这个参数的值。默认不限速。 | cURL 7.15.5 中添加, PHP 5.4.0 有效。 |
CURLOPT_MAX_SEND_SPEED_LARGE | 如果上传的速度超过了此速度(以每秒字节数来统计),即传输过程中累计的平均数,传输就会降速到这个参数的值。默认不限速。 | cURL 7.15.5 中添加, PHP 5.4.0 有效。 |
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_WHATEVER 、CURL_IPRESOLVE_V4 、CURL_IPRESOLVE_V6 ,默认是CURL_IPRESOLVE_WHATEVER 。 | cURL 7.10.8 中添加。 |
CURLOPT_FTP_FILEMETHOD | 告诉 curl 使用哪种方式来获取 FTP(s)服务器上的文件。可能的值有:CURLFTPMETHOD_MULTICWD 、CURLFTPMETHOD_NOCWD 和CURLFTPMETHOD_SINGLECWD 。 | cURL 7.15.1 中添加, PHP 5.3.0 起有效。 |
对于下面的这些$option,$value应该被设置成string:
选项 | 设置的$value | 备注 |
---|---|---|
CURLOPT_CAINFO | 一个保存着1个或多个用来让服务端验证的证书的文件名。这个参数仅仅在和CURLOPT_SSL_VERIFYPEER 一起使用时才有意义。. | 可能需要绝对路径。 |
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 | 连接结束后,比如,调用 curl_close 后,保存 cookie 信息的文件。 | |
CURLOPT_CUSTOMREQUEST | HTTP 请求时,使用自定义的 Method 来代替"GET"或"HEAD"。对"DELETE"或者其他更隐蔽的 HTTP 请求有用。有效值如"GET","POST","CONNECT"等等;也就是说,不要在这里输入整行 HTTP 请求。例如输入"GET /index.html HTTP/1.0rnrn"是不正确的。Note: 不确定服务器支持这个自定义方法则不要使用它。 | |
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_INTERFACE | 发送的网络接口(interface),可以是一个接口名、IP 地址或者是一个主机名。 | |
CURLOPT_KEYPASSWD | 使用CURLOPT_SSLKEY 或CURLOPT_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"操作来发送。要发送文件,在文件名前面加上@前缀并使用完整路径。文件类型可在文件名后以';type=mimetype'的格式指定。这个参数可以是 urlencoded 后的字符串,类似'para1=val1¶2=val2&...',也可以使用一个以字段名为键值,字段数据为值的数组。如果$value是一个数组,Content-Type头将会被设置成multipart/form-data。从 PHP 5.2.0 开始,使用@前缀传递文件时,$value必须是个数组。从 PHP 5.5.0 开始,@前缀已被废弃,文件可通过CURLFile发送。设置CURLOPT_SAFE_UPLOAD 为TRUE 可禁用@前缀发送文件,以增加安全性。 | |
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_PROXY | HTTP 代理通道。 | |
CURLOPT_PROXY_SERVICE_NAME | 代理验证服务的名称。 | cURL 7.34.0 中添加,PHP 7.0.7 起有效。 |
CURLOPT_PROXYUSERPWD | 一个用来连接到代理的"[username]:[password]"格式的字符串。 | |
CURLOPT_RANDOM_FILE | 一个被用来生成 SSL 随机数种子的文件名。 | |
CURLOPT_RANGE | 以"X-Y"的形式,其中X和Y都是可选项获取数据的范围,以字节计。HTTP传输线程也支持几个这样的重复项中间用逗号分隔如"X-Y,N-M"。 | |
CURLOPT_REFERER | 在HTTP请求头中"Referer:"的内容。 | |
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_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-SHA和TLSv1都是可用的加密列表。 | |
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 | 在 由于这个选项包含了敏感的密码信息,记得保证这个PHP脚本的安全。 | |
CURLOPT_SSLKEYTYPE | CURLOPT_SSLKEY 中规定的私钥的加密类型,支持的密钥类型为"PEM"(默认值)、"DER"和"ENG"。 | |
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 中添加,PHP 5.5.0 起有效。 |
CURLOPT_USERPWD | 传递一个连接中需要的用户名和密码,格式为:"[username]:[password]"。 | |
CURLOPT_XOAUTH2_BEARER | 指定 OAuth 2.0 access token。 | cURL 7.33.0 中添加,自 PHP 7.0.7 添加。 |
以下$option,$value应该被设置成数组:
选项 | 可选$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 中添加,自 PHP 5.5.0 起可用。 |
以下$option,$value应该被设置成流资源(例如使用fopen()):
选项 | 可选$value值 |
---|---|
CURLOPT_FILE | 设置输出文件,默认为STDOUT(浏览器)。 |
CURLOPT_INFILE | 上传文件时需要读取的文件。 |
CURLOPT_STDERR | 错误输出的地址,取代默认的STDERR。 |
CURLOPT_WRITEHEADER | 设置 header 部分内容的写入的文件地址。 |
以下$option的$value应该是有效的函数或者闭包:
选项 | $value值 |
---|---|
CURLOPT_HEADERFUNCTION | 设置一个回调函数,这个函数有两个参数,第一个是cURL的资源句柄,第二个是输出的 header 数据。header数据的输出必须依赖这个函数,返回已写入的数据大小。 |
CURLOPT_PASSWDFUNCTION | 设置一个回调函数,有三个参数,第一个是cURL的资源句柄,第二个是一个密码提示符,第三个参数是密码长度允许的最大值。返回密码的值。 |
CURLOPT_PROGRESSFUNCTION | 设置一个回调函数,有五个参数,第一个是cURL的资源句柄,第二个是预计要下载的总字节(bytes)数。第三个是目前下载的字节数,第四个是预计传输中总上传字节数,第五个是目前上传的字节数。 Note:只有设置 返回非零值将中断传输。传输将设置 |
CURLOPT_READFUNCTION | 回调函数名。该函数应接受三个参数。第一个是 cURL resource;第二个是通过选项CURLOPT_INFILE 传给 cURL 的 stream resource;第三个参数是最大可以读取的数据的数量。回调函数必须返回一个字符串,长度小于或等于请求的数据量(第三个参数)。一般从传入的 stream resource 读取。返回空字符串作为EOF(文件结束)信号。 |
CURLOPT_WRITEFUNCTION | 回调函数名。该函数应接受两个参数。第一个是 cURL resource;第二个是要写入的数据字符串。数据必须在函数中被保存。函数必须准确返回写入数据的字节数,否则传输会被一个错误所中断。 |
其他值:
Option | 设置$value为 |
---|---|
CURLOPT_SHARE | curl_share_init()返回的结果。使 cURL 可以处理共享句柄里的数据。 |
返回值
成功时返回TRUE
,或者在失败时返回FALSE
。
更新日志
版本 | 说明 |
---|---|
7.0.7 | 引入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 和CURLSSLOPT_NO_REVOKE 。 |
7.0.0 | 禁用CURLOPT_SAFE_UPLOAD 的选项已被删掉了。所有的 curl 文件的上传都必须使用CURLFile。 |
5.6.0 | 默认CURLOPT_SAFE_UPLOAD 为TRUE 。 |
5.6.0 | 移出CURLOPT_CLOSEPOLICY 和相关的值。 |
5.5.0 | 添加 cURL 资源作为CURLOPT_PROGRESSFUNCTION 回调函数的第一个参数。 |
5.5.0 | 引入CURLOPT_SHARE 。 |
5.3.0 | 引入CURLOPT_PROGRESSFUNCTION 。 |
5.2.10 | 引入CURLOPT_PROTOCOLS , and CURLOPT_REDIR_PROTOCOLS . |
5.2.4 | 引入了CURLOPT_PRIVATE 。 |
5.1.0 | 引入CURLOPT_AUTOREFERER ,CURLOPT_BINARYTRANSFER ,CURLOPT_FTPSSLAUTH ,CURLOPT_PROXYAUTH , and CURLOPT_TIMECONDITION . |
5.0.0 | 引入CURLOPT_FTP_USE_EPRT ,CURLOPT_NOSIGNAL ,CURLOPT_UNRESTRICTED_AUTH ,CURLOPT_BUFFERSIZE ,CURLOPT_HTTPAUTH ,CURLOPT_PROXYPORT ,CURLOPT_PROXYTYPE ,CURLOPT_SSLCERTTYPE , and CURLOPT_HTTP200ALIASES . |
范例
初始化一个新的cURL会话并获取一个网页
上传文件(PHP 5.5.0 后被废弃)
以上例程会输出:
Array ( [name] => Foo ) Array ( [file] => Array ( [name] => test.png [type] => image/png [tmp_name] => /tmp/phpcpjNeQ [error] => 0 [size] => 279 ) )
注释
Note:传递一个数组到CURLOPT_POSTFIELDS
,cURL会把数据编码成multipart/form-data,而然传递一个URL-encoded字符串时,数据会被编码成application/x-www-form-urlencoded。
参见
curl_setopt_array()
为 cURL 传输会话批量设置选项
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!
If you try to upload file to a server, you need do CURLOPT_POST first and then fill CURLOPT_POSTFIELDS.
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 */
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
if you would like to send xml request to a server (lets say, making a soap proxy), you have to set makesure you watch for cache issue: the below code will prevent cache... hope it helps ;)
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 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
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: '-' means stdout -dw
PUT requests are very simple, just make sure to specify a content-length header and set post fields as a string. Example: You can grab the request data on the other side with: DELETE can be done in exactly the same way.
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.
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: See http://www.gnegg.ch/2007/02/the-return-of-except-100-continue/
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: 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.
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: Both the Content-Type and Expect I set will not be in the outgoing headers, but Accept will.
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.
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 isMany 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 ($maxRedirectionhandle, 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.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: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: not this: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: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. Requesting "test.php?bar=@/home/user/test.png" will send "test.png" to example.com. Make sure you remove the leading "@" from user input.If you're getting trouble with cookie handling in curl: - curl manages tranparently cookies in a single curl session - the option makes curl to store the cookies in a file at the and of the curl session - the option 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: 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 LucaIn 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.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, YevgenHello. 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. 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.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 redirectionsOjas OjasviAbout 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: YannIf 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. To get around this, prepend the text string with the NULL character like so: Original source: http://bit.ly/AntMleNote 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.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.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();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!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: 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!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 and following calls to curl_exec() will output to STDOUT again.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.Note that if you want to use a proxy and use it as a _cache_, you'll have to do: else by default Curl puts a "Pragma: no-cache" header in and thus force cache misses for all requests.The page http://curl.haxx.se/libcurl/c/curl_easy_setopt.html at the cURL site has a list of all the CURLOPTS, including many not mentioned here. Also see http://curl.haxx.se/libcurl/php/examples/ for cURL examples in PHP.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.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. Hope this help.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.To send a post as a different content-type (ie.. application/json or text/xml) add this setopt callWhen 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.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: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.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.I've created an example that gets the file on url passed to script and outputs it to the browser. p.s. Make sure that there're no new lines before and after code or script may not work.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.htmThe 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:"));I had problems with the Wikimedia software and sending a POST request where the data was more than 1024 bytes long. I traced this to cURL adding: Expect: 100-continue to the headers. I added curl_setopt($ch,CURLOPT_HTTPHEADER,array("Expect:")); and that suppresses the Expect line.To find what encoding a given HTTP POST request uses is easy -- passing an array to CURLOPT_POSTFIELDS results in multipart/form-data: Passing a URL-encoded string will result in application/x-www-form-urlencoded: 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.A note on the way Curl posts files...
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!