最近,因为Web应用程序迁移到云服务器上,发生了一个致命问题。原有服务器的PHP环境为5.5,云服务的PHP环境为5.6。当时,抓取远程内容的函数用的是:get_file_content(),迁移之后,发现PDF文件打不开,经过调试,原来PHP5.5时,抓取URL远程内容时,不会自动gzip压缩内容,而PHP5.6时,抓取URL远程内容时,会自动gzip压缩,恰恰 get_file_content(),不能自动通过gizp压缩的方式抓取,故导致无发抓取远程内容。
解决方案:使用curl方式远程抓取,代码如下
/**
*param String $url url地址
*param Array $param 请求参数
*param Boolen $ispost 请求方式:true-POST请求|false-GET请求
*param Boolen $gzip 是否gizp压缩方式请求:true-是|false-否
*/
function get_curl($url, $params = '', $ispost = false,$gzip=false)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($ispost) {
if (is_array($params)) $params = http_build_query($params);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_URL, $url);
} else {
if ($params) {
if (is_array($params)) $params = http_build_query($params);
curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
}
if($gzip){
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
}
$response = curl_exec($ch);
if ($response === FALSE) {
return false;
}
curl_close($ch);
return $response;
}