首页 > 开发 > PHP > 正文

php CURLOPT错误Warning: curl_setopt() [function.curl-setopt]:...

2024-05-04 21:59:28
字体:大 中 小
来源:转载
供稿:网友

在我们使用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转向等就会出现文中提到的错误信息.

在查了相关资料后,很快找到了解决办法,http://www.php.net/manual/en/function.curl-setopt.php,这些方法都在php官方帮助里有.

具体做法是在curl语句用不使用curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true),在php函数中自定义一个函数,代码如下:

  1. function curl_redir_exec($ch,$debug="") 
  2. { 
  3. static $curl_loops = 0; 
  4. static $curl_max_loops = 20; 
  5. if ($curl_loops++ >= $curl_max_loops) 
  6. { 
  7. $curl_loops = 0; 
  8. return FALSE; 
  9. } 
  10. curl_setopt($ch, CURLOPT_HEADER, true); 
  11. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
  12. $data = curl_exec($ch); 
  13. $debbbb = $data; 
  14. list($header, $data) = explode("\n\n", $data, 2); 
  15. $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
  16. if ($http_code == 301 || $http_code == 302) { 
  17. $matches = array(); 
  18. preg_match('/Location:(.*?)\n/', $header, $matches); 
  19. $url = @parse_url(trim(array_pop($matches))); 
  20. //print_r($url); 
  21. if (!$url) 
  22. { 
  23. //couldn't process the url to redirect to 
  24. $curl_loops = 0; 
  25. return $data; 
  26. } 
  27. $last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL)); 
  28. /*    if (!$url['scheme']) 
  29. $url['scheme'] = $last_url['scheme']; 
  30. if (!$url['host']) 
  31. $url['host'] = $last_url['host']; 
  32. if (!$url['path']) 
  33. $url['path'] = $last_url['path'];*/ 
  34. $new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:''); 
  35. curl_setopt($ch, CURLOPT_URL, $new_url); 
  36. //    debug('Redirecting to', $new_url); 
  37. return curl_redir_exec($ch); 
  38. } else {//开源软件:Vevb.com 
  39. $curl_loops=0; 
  40. return $debbbb; 
  41. } 
  42. } 

函数定义好后,curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true)这条语句替换为curl_redir_exec($ch).

这样以后,我想你的PHP文件应该不会提示错误了,关于这段代码,在提供PHP官方连接用可以找到.

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表