curl跟随重定向错误

14
我收到了这个错误信息:

当 safe_mode 开启或设置 open_basedir 时,无法激活 CURLOPT_FOLLOWLOCATION。

我的Web主机已关闭 safe_mode。
open_basedir 是 ""。
我该如何解决这个问题?

您可以轻松提取所引用的网站链接:https://dev59.com/yXA75IYBdhLWcg3wAUF9#3520085 - user669677
请参考以下链接的回答:https://dev59.com/N2w05IYBdhLWcg3w9mhW#6918742 - T.Todua
6个回答

12

解决方法是在PHP代码中实现重定向。

这里是我的自己的实现,它有两个已知的限制:

  1. 它将强制使用CURLOPT_RETURNTRANSFER
  2. 它与CURLOPT_HEADERFUNCTION不兼容

代码如下:

function curl_exec_follow(/*resource*/ &$ch, /*int*/ $redirects = 20, /*bool*/ $curlopt_header = false) {
    if ((!ini_get('open_basedir') && !ini_get('safe_mode')) || $redirects < 1) {
        curl_setopt($ch, CURLOPT_HEADER, $curlopt_header);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $redirects > 0);
        curl_setopt($ch, CURLOPT_MAXREDIRS, $redirects);
        return curl_exec($ch);
    } else {
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FORBID_REUSE, false);

        do {
            $data = curl_exec($ch);
            if (curl_errno($ch))
                break;
            $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if ($code != 301 && $code != 302)
                break;
            $header_start = strpos($data, "\r\n")+2;
            $headers = substr($data, $header_start, strpos($data, "\r\n\r\n", $header_start)+2-$header_start);
            if (!preg_match("!\r\n(?:Location|URI): *(.*?) *\r\n!", $headers, $matches))
                break;
            curl_setopt($ch, CURLOPT_URL, $matches[1]);
        } while (--$redirects);
        if (!$redirects)
            trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
        if (!$curlopt_header)
            $data = substr($data, strpos($data, "\r\n\r\n")+4);
        return $data;
    }
}

3
在我的情况下,我需要在do循环中的if条件语句中添加&& $code!=303(See Other),以复制我的CURLOPT_FOLLOWLOCATION=true的行为。 - Ruben
相关博客文章cURL:在启用safe_mode或设置open_basedir的情况下跟随位置(由Slopjong于2012年3月31日发布) - 它也不完美,但如果有人想要审查代码,可能会有所帮助。 - hakre

5
这个警告信息只会在 ext/curl/interface.c 中打印。
if ((PG(open_basedir) && *PG(open_basedir)) || PG(safe_mode)) {
  if (Z_LVAL_PP(zvalue) != 0) {
    php_error_docref(NULL TSRMLS_CC, E_WARNING, "CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set");
    RETVAL_FALSE;
    return 1;
  }
}

从if条件中可以看出,必须启用open_basedir或safe_mode之一。


有没有什么方法可以克服这个问题?例如自定义跟随位置函数或类似的东西。 - embedded
4
您可以使用 curl_getinfo($ch, CURLINFO_HTTP_CODE),如果返回301或302,则获取Location标头。 - VolkerK
这是zsalab的实现。 - dolmen

2

我之前遇到过类似的情况,并发现了以下解决方案。如果你大致知道你将被重定向到哪里,这可能适用于你。

    function curl($url, $postVars)
{
    $go = curl_init($url);
    curl_setopt ($go, CURLOPT_URL, $url);
    curl_setopt($go, CURLOPT_VERBOSE, 1);

    //follow on location problems
    if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off'))
    {
        curl_setopt ($go, CURLOPT_FOLLOWLOCATION, $l);
        $syn = curl_exec($go);
        if(curl_error($go))
            return false;
    }
    else
        $syn = curl_redir_exec($go, $postVars);
    curl_close($go);
    return $syn;
}

function curl_redir_exec($ch, $postVars)
{
    static $curl_loops = 0;
    static $curl_max_loops = 20;
    if ($curl_loops++>= $curl_max_loops)
    {
        $curl_loops = 0;
        return FALSE;
    }
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postVars);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

    $data = curl_exec($ch);
    if(curl_error($ch))
        return false;
    list($header, $data) = explode("\n\r", $data, 2);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    $redirect_page = "[0-9]*.html";
    $base_redirect = "http://example.com/";

    if ($http_code == 301 || $http_code == 302)
    {
        $matches = array();
        $pregs = eregi($redirect_page, $data, $matches);
        $new_url = $base_redirect . $matches[0];
        if (!$new_url)
        {
            //couldn't process the url to redirect to
            $curl_loops = 0;
            return $data;
        }
        curl_setopt($ch, CURLOPT_URL, $new_url);

        return curl_redir_exec($ch, $postVars);
    }
    else
    {
        $curl_loops=0;
        return $data;
    }
}

1

从未在真实环境中测试过,但使用curl_exec更加透明(头部和返回选项没有问题)。

function curl_exec_follow(/*resource*/ $ch, /*int*/ $maxredirect = 5) {
    if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    } else {
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        $newurl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

        $rch = curl_copy_handle($ch);
        curl_setopt($rch, CURLOPT_HEADER, true);
        curl_setopt($rch, CURLOPT_NOBODY, true);
        curl_setopt($rch, CURLOPT_RETURNTRANSFER, true);
        do {
            curl_setopt($rch, CURLOPT_URL, $newurl);
            $header = curl_exec($rch);
            if (curl_errno($rch)) {
                $code = 0;
            } else {
                $code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
                if ($code == 301 || $code == 302) {
                    preg_match('/Location:(.*?)\n/', $header, $matches);
                    $newurl = trim(array_pop($matches));
                } else {
                    $code = 0;
                }
            }
        } while ($code && $maxredirect--);
        curl_close($rch);
        curl_setopt($ch, CURLOPT_URL, $newurl);
    }
    return curl_exec($ch);
}

这个实现有两个问题:1. 如果出现错误,它将会丢失;2. 最终URL的请求会被执行两次(一次只是为了获取头信息,一次是完整请求)。 - dolmen
ini_get('safe_mode' == 'Off') 这里有个打字错误(括号应该包含'safe_mode',而且不会在所有地方都起作用)。 - Ruben

1

提示:

所有带有代码的答案都手动解析curl请求中的头部,以查找Location:头部。

但是,自从PHP 5.3.7以来,有一个选项CURLINFO_REDIRECT_URL可与curl_getinfo()一起使用。无需两次请求,如果您不想要头文件,则无需启用它们,也无需正则表达式。


0
如果您已经配置了一个$curl实例,并且只想模拟启用FOLLOWLOCATION的curl_exec,则可以使用此代码:
function curl_follow_exec($curl, $url = null)
{
    curl_setopt($curl, CURLOPT_HEADER, true);
    if (!is_null($url))
    {
        $opts = array (
            CURLOPT_URL => $url,
            CURLOPT_POST => false,
            CURLOPT_PUT => false,
        );
        curl_setopt_array($curl, $opts);
    }
    $data = curl_exec($curl);
    $status = curl_getinfo($curl);
    $arr = explode("\r\n\r\n", $data);
    while (strpos(reset($arr), 'HTTP/1.1 100 Continue') !== false)
    {
        array_shift($arr);
    }
    $header = $arr[0];
    $body = implode("\r\n", array_slice($arr, 1));
    if ($status['http_code'] == 301 || $status['http_code'] == 302)
    {
        $matches = array ();
        preg_match("/(Location:|URI:)[^(\n)]*/", $header, $matches);
        $url = trim(str_replace($matches[1], "", $matches[0]));
        return curl_follow_exec($curl, $url);
    }
    return $body;
}

注意:如果您已经指定了选项,请在调用此函数时不要提供URL,它仅用于递归目的。
我从被接受的答案中获得了灵感,并添加了一些内容来管理多个标题。
这个函数就像ie6的一个丑陋的黑客:如果可以的话,请更改您的托管 :-)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接