curl 跟随位置错误

标签 curl php

我收到此错误消息:

CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set in.

我的虚拟主机上的安全模式已关闭。

open_basedir 是“”。

我该如何解决?

最佳答案

解决方法是在 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;
    }
}

关于 curl 跟随位置错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2511410/

相关文章:

curl - cURL 上的 -u 标志实际上在做什么?

php - 使用 https ://{shop}. myshopify.com/admin/oauth/access_token 时,Shopify 出现错误 400 [Bad Request]

php - 通过唯一编号定义用户

php - 如何在 Docker 容器中测试 PHP API

linux - 如何使用 grep 多重模式并删除第一个模式

curl - 更新 Paypal 计费计划(payment_definitions)

php - 如何在 Amazon EC2 免费套餐上启用 cURL 扩展

javascript - 将 JS 变量等同于 json 编码的 php 数组值,无论索引如何

php - 如何在html中隐藏不需要的空白

php - 如何显示包含某些数据的mysql行?