zoukankan      html  css  js  c++  java
  • 带超时+POST/GET方式的获取远程文件,利用file_get_contents

    这个函数也是项目中写的,提取出来,恐以后用到,还比较方便

    /**
     * file_get_contents方式获取远程文件
     * @param $url 可以是带参数的url
     * @param $timeout 设置超时
     * @param $params 参数字符串,如a=2&b=3,通常用http_build_query生成
     * @param $method 'GET','POST','' 为空等表示不对参数处理
     * @param $times
     * @return string|boolean
     */
    function get_remote_file($url = '', $timeout = 6, $params = '', $method = 'GET', $times = 3){
    	//提交方式
    	$method	=	strtoupper($method);
    	//基本选项
    	$opts['http'] = array(
    			'method'=>$method,
    			'timeout'=>$timeout,//设置超时时间(秒)
    	);
    	
    	//判断参数提交方式
    	if(!empty($params)){
    		if('POST' == $method){
    			$opts['http']['content']	=	$params;
    		}elseif('GET' == $method){
    				$url	.=	((false === strpos($url, '?'))?'?':'&').$params;
    		}
    	}
    	$context	=	stream_context_create($opts);
    	$cnt	=	0;
    	$file	=	false;
    	//尝试$times次获取远程文件
    	while($cnt < $times && ($file = file_get_contents($url, false, $context)) === false)$cnt++;
    
    	return $file;
    }
    
  • 相关阅读:
    html 注释和特殊字符
    html 锚点链接
    html 链接标签
    spring 利用工厂模式解耦
    html 路径
    html 图像标签
    html div和span标签
    html 文本格式化标签
    P5358 [SDOI2019]快速查询
    luoguP2679 子串
  • 原文地址:https://www.cnblogs.com/ppoo24/p/1872981.html
Copyright © 2011-2022 走看看