在我们使用php curl函数时提示warning: curl_setopt() [function.curl-setopt]: curlopt_followlocation cannot be activated when in safe_mode or an open_basedir is set…错误,下面我就来介绍碰到此问题要如何来排除问题吧。
如果当你在php中运行 curlopt_followlocation 然后得到php提示错误信息为:
warning: curl_setopt() [function.curl-setopt]: curlopt_followlocation cannot be activated when in safe_mode or an open_basedir is set…
错误中提到两个关键safe_mode和 open_basedir,如果你是虚拟主机的没有设置appche的权限是不能通过修改服务器配置来解决问题的,
一般来说,服务器配置safe_mode都为off,然后为了一些安全对用户有一些限制,通过设置open_basedir来限制虚拟主机用户的php执行文件夹,
因此当你使用curlopt_followlocation (php curl函数,深层抓取数据)的时候,一旦有301转向等就会出现文中提到的错误信息.
在查了相关资料后,很快找到了解决办法
具体做法是在curl语句用不使用curl_exec函数
curl_setopt($ch, curlopt_followlocation, true);
自定义一个curl_exec函数
function curlexec(/* array */$curloptions='', /* array */$curlheaders='', /* array */$postfields='')
{
$newurl = '';
$maxredirection = 10;
do
{
if ($maxredirection<1) die('error: reached the limit of redirections');
$ch = curl_init();
if (!empty($curloptions)) curl_setopt_array($ch, $curloptions);
if (!empty($curlheaders)) curl_setopt($ch, curlopt_httpheader, $curlheaders);
if (!empty($postfields))
{
curl_setopt($ch, curlopt_post, 1);
curl_setopt($ch, curlopt_postfields, $postfields);
}
if (!empty($newurl)) curl_setopt($ch, curlopt_url, $newurl); // redirect needed
$curlresult = curl_exec($ch);
$code = curl_getinfo($ch, curlinfo_http_code);
if ($code == 301 || $code == 302 || $code == 303 || $code == 307)
{
preg_match('/location:(.*?)\n/i', $curlresult, $matches);
$newurl = trim(array_pop($matches));
curl_close($ch);
$maxredirection--;
continue;
}
else // no more redirection
{
$code = 0;
curl_close($ch);
}
}
while($code);
return $curlresult;
}