php如何增强file_get_contents函数的兼容性相关介绍

巴扎黑
发布: 2023-03-14 20:50:02
原创
1583 人浏览过


php增强file_get_contents的兼容性, 优先选择CURL拓展

function rlib_file_get_contents($url, $referer = null, $timeout = 10){
	static $curl_enabled = -1;
	if ($curl_enabled == -1){
		$curl_enabled = (extension_loaded('curl') && function_exists('curl_exec')) ? 1 : 0;
	}
	$contents = null;
	if ($curl_enabled == 1){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_REFERER, ($referer == null ? $url : $referer));
		curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
		//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept-Encoding: gzip, deflate'));
	    	//curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
		$contents = curl_exec($ch);	
		if ($contents == FALSE){
			global $g_lastError;
			$g_lastError = curl_error($ch);
			$contents = null;
		}
		curl_close($ch);
	} else {
		$contents = file_get_contents($url, false, stream_context_create(array(
			'http' => array(
				'timeout' => $timeout,
				'header' => 'Referer: ' . ($referer == null ? $url : $referer) . '\r\n' .
							'User-Agent: ' . $_SERVER["HTTP_USER_AGENT"] . '\r\n'
			)
		)));
		if ($contents == FALSE){
			global $g_lastError;
			$g_lastError = 'file_get_contents出错';
			$contents = null;
		} else {
			//$contents = mb_convert_encoding($contents, 'UTF-8', mb_detect_encoding($contents, 'UTF-8, GBK, GB2312', true));
		}
	}
	return $contents;
}
登录后复制


以上是php如何增强file_get_contents函数的兼容性相关介绍的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!