起因:
根据文档中https://www.php.net/manual/zh/function.fsockopen.php

fsockopen这里的time是连接时间,可能不会有效果。坑爹啊!!!

貌似要使用 stream_set_timeout(): stream_set_timeout() 函数设置的是 读取/写入数据超时

.....stream_set_timeout($fp, 10);while ( ($str = @fread($fp, 4096)) ||  (!feof($fp))){$Content .= $str;$info = stream_get_meta_data($fp);if ($info['timed_out']) {return array('errno'=>'001', 'errstr'=>'Connection timed out!', 'status'=>'unknown', 'content'=>$Content) ;}}
···

全部:

<?phpif(!function_exists('fsockopen'))
{throw new Exception('To send http request, you have to open socket extension or enable fsockopen function.') ;
}class Http {protected $url = null ;protected $timeout = 10 ;public function __construct($url = '', $timeout=10){if(!empty($url)) $this->url = $url ;$this->timeout = $timeout ;}public function setUrl($url){$this->url = $url ;}public function getUrl(){return $this->url ;}public function setTimeout($timeout){$this->timeout = $timeout ;}public function getTimeout(){return $this->timeout ;}//抓取网页内容public function getResponse($post=null, $cookie=null, $header=null){if(empty($this->url)){return array('errno'=>'000','errstr'=>'Url is empty','status'=>'error') ;}if(preg_match('/^https?:\/\//i', $this->url, $matchs)){$http = strtolower($matchs[0]) ;}if($http == 'https'){$ssl = true ;}else{$ssl = false ;}$url = preg_replace('/^https?:\/\//i', '', $this->url);$temp = explode('/', $url);$host = array_shift($temp);$host = empty($host)?'localhost':$host ;$path = '/'.implode('/', $temp);$temp = explode(':', $host);$host = $temp[0];$port = isset($temp[1]) ? $temp[1] : (!$ssl?80:443);//http协议头if( !empty($post) ){$data = $this->createPost($post) ;$headers = "POST {$path} HTTP/1.1\r\n";$headers .= "Host: {$host}\r\n";$headers .= "Referer: {$path}\r\n";//加入cookieif(!empty($cookie)){$headers .= "Cookie: " . $this->createCookie($cookie) . "\r\n" ;}$headers .= "Content-Type: application/json\r\n";$headers .= "Content-Length: ".strlen($data)."\r\n";$headers .= $header ? $header . "\r\n" : '' ;$headers .= "Connection: Close\r\n\r\n";$headers .= $data."\r\n";}else{$headers = "GET {$path} HTTP/1.1\r\n" ;$headers .= "Host: {$host}\r\n" ;$headers .= "Accept: */*\r\n" ;$headers .= "Referer:{$url}\r\n" ;//加入cookieif(!empty($cookie)){$headers .= "Cookie: " . $this->createCookie($cookie) . "\r\n" ;}$headers .= "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)\r\n" ;$headers .= $header ? $header . "\r\n" : '' ;$headers .= "Connection: Close\r\n\r\n" ;}$fp = @fsockopen(($ssl?'ssl://':'').$host, $port, $errno, $errstr, $this->timeout);if ($fp){@fputs($fp, $headers);}else {return array('errno'=>$errno, 'errstr'=>$errstr, 'status'=>'error') ;}$Content = '';// 设置写入超时时间stream_set_timeout($fp, 10);while ( ($str = @fread($fp, 4096)) ||  (!feof($fp))){$Content .= $str;$info = stream_get_meta_data($fp);if ($info['timed_out']) {return array('errno'=>'001', 'errstr'=>'Connection timed out!', 'status'=>'unknown', 'content'=>$Content) ;}}@fclose($fp);//保存cookieunset($matchs) ;if(preg_match("/Set-Cookie:(.*?)\r\n/is",$Content,$matchs)){$cookie = $matchs[1] ;}//重定向if(preg_match("/^HTTP\/\d.\d (301|302) [\w\s]*\r\n/is",$Content)){if(preg_match("/Location:(.*?)\r\n/is",$Content,$murl)){$murl[1] = trim(str_replace("\r\n",'',$murl[1]));if( $this->url != $murl[1]){if(!preg_match('/^https?:\/\//i', $murl[1])){$murl[1] = $http . $host . $murl[1];}$this->setUrl($murl[1]) ;return $this->getResponse($post, $cookie, $header) ;}}}//读取内容if(preg_match("/^HTTP\/\d.\d ([\d]*) (\w*)/is", $Content, $matchs)){if($matchs[1] == '200'){preg_match("/Content-Type:(.*?)\r\n/is", $Content, $murl);$contentType = empty($murl) ? '' : trim($murl[1]) ;$Content = explode("\r\n\r\n", $Content, 2) ;$Content = $Content[1] ;$output = array('errno'=>$matchs[1], 'errstr'=>$matchs[2], 'status'=>'ok', 'content'=>$Content) ;}else {$Content = explode("\r\n\r\n", $Content, 2) ;$Content = $Content[1] ;$output = array('errno'=>$matchs[1], 'errstr'=>$matchs[2], 'status'=>'found', 'content'=>$Content) ;}//Remove header(number \r\n) and footer(0\r\n\r\n)$output['content'] = preg_replace("/^[0-9a-f]+\r\n/is", "", $output['content']) ;$output['content'] = preg_replace("/\r\n0\r\n\r\n$/is", "", $output['content']) ;return $output ;}else{return array('errno'=>'001', 'errstr'=>'Unknown error', 'status'=>'unknown', 'content'=>$Content) ;}}//生成POST字符串public function createPost($post){if(!is_array($post) && !is_object($post)){return $post ;}$ret = '' ;foreach($post as $key=>$value){if(is_array($value)){continue ;}else{$ret .= "{$key}=" . urlencode($value) . "&" ;}}if(!empty($ret)){$ret = substr($ret, 0, -1) ;}return $ret ;}//生成Cookie字符串public function createCookie($cookie){if(!is_array($cookie) && !is_object($cookie)){return $cookie ;}$ret = '' ;foreach($cookie as $key=>$value){if(is_array($value)){continue ;}else{$ret .= "{$key}=" . urlencode($value) . ";" ;}}if(!empty($ret)){$ret = substr($ret, 0, -1) ;}return $ret ;}/**@Description: POST发送文件 @Parameter: url, file path, form(array)@Return value: -1, ERROR, Response strings@Example: sendFile("http://localhost/atv/upload.php","F:\yaxiong\wwwroot\ProductExportSat-03-28-101754.xls",'file',array('key1'=>'value1','key2'=>'value2')) ;*/public function sendFile($file_path, $upload_name, $form=null){$url = preg_replace('^http://', '', $this->url);$temp = explode('/', $url);$host = array_shift($temp);$host = empty($host)?'localhost':$host ;$path = '/'.implode('/', $temp);$temp = explode(':', $host);$host = $temp[0];$port = isset($temp[1]) ? $temp[1] : 80;//http协议头//$data = $this->createPost($post) ;$boundary = "---------------------------" . substr(md5(time()), -12 );$data = $this->createFileData($file_path, $boundary, $upload_name, $form) ;if($data == -1){return -1 ;//错误处理}$headers = "POST {$path} HTTP/1.1\r\n";$headers .= "Host: {$host}\r\n";//$headers .= "Referer: {$path}\r\n";$headers .= "Accept: */*\r\n";//$headers .= "Connection: Keep-Alive\r\n";$headers .= "Cache-Control: no-cache\r\n";$headers .= "Content-Type: multipart/form-data; boundary={$boundary}\r\n";$headers .= "Content-Length: ".strlen($data)."\r\n";$headers .= "Connection: Keep-Alive\r\n\r\n" ;$headers .= $data . "\r\n";$fp = @fsockopen($host, $port, $errno, $errstr, 30);if ($fp){@fputs($fp, $headers);}$Content = '';while ($str = @fread($fp, 4096)){$Content .= $str;}@fclose($fp);//重定向if(preg_match("/^HTTP\/\d.\d 301 Moved Permanently/is",$Content)){if(preg_match("/Location:(.*?)\r\n/is",$Content,$murl)){return $this->getContent($murl[1]);}}//读取内容if(preg_match("/^HTTP\/\d.\d 200 OK/is",$Content)){preg_match("/Content-Type:(.*?)\r\n/is",$Content,$murl);$contentType=trim($murl[1]);$Content=explode("\r\n\r\n",$Content,2);$Content=$Content[1];}else{$Content="ERROR" ;}//Remove header(number \r\n) and footer(0\r\n\r\n)$Content = preg_replace("/^[0-9a-f]+\r\n/is", "", $Content) ;$Content = preg_replace("/\r\n0\r\n\r\n$/is", "", $Content) ;return $Content;}//构造文件数据public function createFileData($file_path, $boundary, $upload_name, $form=null){//读取文件数据$fname = basename( $file_path );$fp = @fopen( $file_path, "r" );if($fp){$data = fread( $fp, filesize( $file_path ) );fclose ($fp);}else{return -1 ;}$file_data = "";$file_data .= "--{$boundary}\r\n";$file_data .= "Content-Disposition: form-data; name=\"{$upload_name}\"; filename=\"$fname\"\r\n";$file_data .= "Content-Type: application/octet-stream\r\n" ;$file_data .= "Content-Transfer-Encoding: binary\r\n\r\n";$file_data .= "{$data}\r\n";$file_data .= "--{$boundary}--\r\n";//构建form数据if(is_array($form)){$form_data = "";foreach( $form as $key => $value ){$row = "";$row .= "--{$boundary}\r\n";$row .= "Content-Disposition: form-data; name=\"{$key}\"\r\n\r\n";$row .= "{$value}\r\n";$form_data .= $row ;}}return $file_data . "\r\n" . $form_data ;}
}
?>

fsockopen设置超时时间相关推荐

  1. HttpClient 如何设置超时时间

    今天分享一个巨坑,就是 HttpClient.这玩意有多坑呢?就是每个版本都变,近日笔者深受其害. 先看一下代码,我要发送请求调用一个c++接口. public static String doPos ...

  2. 【Java 网络编程】服务器端 ServerSocket 配置 ( 端口复用 | 缓冲区设置 | 超时时间 | 性能权重 | 端口绑定 )

    文章目录 I ServerSocket 端口号绑定参数 II ServerSocket 复用绑定端口设置 III ServerSocket 设置缓冲区大小 IV ServerSocket 设置超时时间 ...

  3. python给函数设置超时时间_在 Linux/Mac 下为Python函数添加超时时间的方法

    我们在使用 requests 这类网络请求第三方库时,可以看到它有一个参数叫做 timeout ,就是指在网络请求发出开始计算,如果超过 timeout 还没有收到返回,就抛出超时异常.(当然存在特殊 ...

  4. php如何发起远程请求,PHP请求远程地址如何设置超时时间

    PHP请求远程地址设置超时时间的方法:1.[file_get_contents]请求超时设置:2.fopen请求超时设置:3.curl请求超时设置. [相关学习推荐:php编程(视频)] PHP请求远 ...

  5. 同时设置超时时间_刚入职的小菜鸡,设错了RPC超时,搞了个线上事故

    上面这张监控图,对于服务端的研发同学来说再熟悉不过了.在日常的系统维护中,『服务超时』应该属于监控报警最多的一类问题. 尤其在微服务架构下,一次请求可能要经过一条很长的链路,跨多个服务调用后才能返回结 ...

  6. python给函数设置超时时间_在 Linux/Mac 下为Python函数添加超时时间

    我们在使用 requests 这类网络请求第三方库时,可以看到它有一个参数叫做timeout,就是指在网络请求发出开始计算,如果超过 timeout 还没有收到返回,就抛出超时异常.(当然存在特殊情况 ...

  7. 调用webservice 设置超时时间

    前段时间自己写了个程序,调用webservice,今天早上一执行,速度是相当的慢,一开始以为是程序的问题,后来跟踪一看,原来是调用webservice出现问题,放置webservice的服务器关掉了, ...

  8. apache httpclient4 设置超时时间

    2019独角兽企业重金招聘Python工程师标准>>> apache httpclient4 设置超时时间 旧的方法(已被禁用) CloseableHttpClient httpcl ...

  9. httpclient 设置超时时间_面试官:技术选型,HttpClient还是OkHttp?

    你知道的越多,不知道的就越多,业余的像一棵小草! 你来,我们一起精进!你不来,我和你的竞争对手一起精进! 编辑:业余草 来源:juejin.im/post/6844904040644476941 推荐 ...

最新文章

  1. 源码安装tensorflow
  2. 专业的秘密 | 南方医科大学生物信息学专业
  3. php正则表达式判断url,判断url的正则表达式
  4. ASP.NET Web API 基本操作(CRUD)
  5. 为什么一个星期是7天
  6. 周一 周五 记录_6.12日独家提示买入的 民丰特纸,属于突破年线的股票当天,所以我们买入后小幅盈利 于今天周一6月月15日冲高逢高获利卖出...
  7. 前缀和与差分的使用(新手快速入门)
  8. recover 没有捕获异常_defer + recover 捕获所有异常
  9. linux操作系统字段含义,Linux系统 /etc/fstab各个字段含义解释
  10. java camel swagger,Swagger将下划线转换为camelcase
  11. 转换为正整数_进制之间的转换
  12. python解zuobiaoxi方程_从马尔可夫链到蒙特卡洛-Metropolis方法(Python)
  13. *C#(WPF)--矩阵拖动和矩阵动画(拖动展开,不足动画效果)
  14. 梅创社c语言课本答案解析,c语言程序设计第2版) 教学课件 作者 梅创社答案 第一章答案.docx...
  15. Unity调用打印机
  16. 五、Ceph之RBD存储使用
  17. zabbix Lack of free swap space
  18. ps打开图片的三种方式 同步部分基本操作方式
  19. 微信扫描二维码跳转手机默认浏览器打开下载app的链接是怎么实现的
  20. 中国椭圆形板簧行业市场供需与战略研究报告

热门文章

  1. 将DataTable中的数据保存到Excel
  2. Unity资源加载方式
  3. 在matlab中三维表面采用,在Matlab中插入三维圆柱体的表面
  4. 八代服务器芯片组,Intel八代酷睿全曝光:主板前所未有的混乱
  5. mysqloffset函数
  6. 教你正确整治流氓APP,做好安卓手机权限管理来保护隐私
  7. javascript closure
  8. 苹果id可以彻底注销吗_公司注销之后商标可以转让给个人吗?
  9. 腾讯云开团!2018年6月份最新福利,360元买4年,赶紧开撸
  10. 安卓恶意代码(软件)检测2012-2013年论文研究