curl_setopt()TCPDF的CURLOPT_FOLLOWLOCATION问题

时间:2012-04-13 09:23:09

标签: php curl tcpdf

我已将一个网站迁移到另一个网站托管。当我在localhost上测试时一切正常,但是当我在线试用时,我收到以下内容:

curl_setopt() [<a href='function.curl-setopt'>function.curl-setopt</a>]: 
    CURLOPT_FOLLOWLOCATION cannot be activated when safe_mode is enabled or 
    an open_basedir is set

当我尝试使用TCPDF生成PDF文件时(7542行生成错误)

7534             if ($imsize === FALSE) {
7535                 if (function_exists('curl_init')) {
7536                     // try to get remote file data using cURL
7537                     $cs = curl_init(); // curl session
7538                     curl_setopt($cs, CURLOPT_URL, $file);
7539                     curl_setopt($cs, CURLOPT_BINARYTRANSFER, true);
7540                     curl_setopt($cs, CURLOPT_FAILONERROR, true);
7541                     curl_setopt($cs, CURLOPT_RETURNTRANSFER, true);
7542                     curl_setopt($cs, CURLOPT_FOLLOWLOCATION, true);

我该怎么做才能避免这种情况?

3 个答案:

答案 0 :(得分:1)

如果托管公司/部门不愿意关闭safe_mode,则解决方法可能是在php.net上发现的这个有用的代码段http://php.net/manual/ro/function.curl-setopt.php#71313

function curl_redir_exec($ch)
{
    static $curl_loops = 0;
    static $curl_max_loops = 20;
    if ($curl_loops++ >= $curl_max_loops) {
        $curl_loops = 0;
        return FALSE;
    }
    curl_setopt_array($ch, array(CURLOPT_HEADER => true, CURLOPT_RETURNTRANSFER => true));
    $data = curl_exec($ch);
    list($header, $data) = explode("\n\n", $data, 2);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($http_code == 301 || $http_code == 302) {
        $matches = array();
        preg_match('/Location:(.*?)\n/', $header, $matches);
        $url = @parse_url(trim(array_pop($matches)));
        if (!$url) {  //couldn't process the url to redirect to
            $curl_loops = 0;
            return $data;
        }
        $last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
        foreach(array('scheme', 'host', 'path') as $component) {
            if (!$url[$component]) {
                $url[$component] = $last_url[$component];
            }
        }
        $new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] 
                 . ($url['query'] ? '?' . $url['query'] : '');
        curl_setopt($ch, CURLOPT_URL, $new_url);
        return curl_redir_exec($ch);
    } else {
        $curl_loops = 0;
        return $data;
    }
}

答案 1 :(得分:0)

错误消息告诉您错误:

  启用safe_mode或设置open_basedir时,无法激活

CURLOPT_FOLLOWLOCATION

您应该能够以这种方式获取当前配置:

var_dump(array_map('ini_get', array('safe_mode', 'open_basedir')));

要删除错误,请与您的主机托管部门联系,告诉他们您对PHP设置的技术要求。如果主机无法满足您的要求,您就为PHP脚本选择了错误的主机。

答案 2 :(得分:0)

您应该关闭主机中的safe_modeopen_basedir。您可以通过托管支持询问。如果它不可用,您可以将open_basedir的值更改为(0)。

示例:

    curl_setopt($rConnect, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($rConnect, CURLOPT_FOLLOWLOCATION, 1);

应该改为

    curl_setopt($rConnect, CURLOPT_RETURNTRANSFER, 0);
    curl_setopt($rConnect, CURLOPT_FOLLOWLOCATION, 0);