欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php之curl设置超时实例

程序员文章站 2022-06-12 20:30:29
本文实例讲述了php中curl超时设置方法。分享给大家供大家参考。具体实现方法如下: 访问http方式很多,可以使用curl, socket, file_get_cont...

本文实例讲述了php中curl超时设置方法。分享给大家供大家参考。具体实现方法如下:

访问http方式很多,可以使用curl, socket, file_get_contents() 等方法。
在访问http时,需要考虑超时的问题。

curl访问http:

curl 是常用的访问http协议接口的lib库,性能高,还有一些并发支持的功能等。 
curl_setopt($ch, opt) 可以设置一些超时的设置,主要包括:   
① (重要) curlopt_timeout 设置curl允许执行的最长秒数。     
② (重要) curlopt_timeout_ms 设置curl允许执行的最长毫秒数。   
(在curl 7.16.2中被加入。从php 5.2.3起可使用)
③  curlopt_connecttimeout 在发起连接前等待的时间,如果设置为0,则无限等待。
④ curlopt_connecttimeout_ms 尝试连接等待的时间,以毫秒为单位。如果设置为0,则无限等待。  (在curl 7.16.2中被加入。从php 5.2.3开始可用) 
⑤ curlopt_dns_cache_timeout 设置在内存中保存dns信息的时间,默认为120秒。
 
1. curl普通秒级超时:

复制代码 代码如下:
$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']);

2. curl普通秒级超时使用:

复制代码 代码如下:
curl_setopt($ch, curlopt_timeout,60);
 

3. curl如果需要进行毫秒超时,需要增加:

复制代码 代码如下:
curl_easy_setopt(curl, curlopt_nosignal,1l);     
 //或者     
 curl_setopt ( $ch,  curlopt_nosignal,true);//支持毫秒级别超时设置

 
希望本文所述对大家的php程序设计有所帮助。