【问题标题】:PHP - file_get_contents for jpeg file returning false when the URL works on a browserPHP - 当 URL 在浏览器上工作时,jpeg 文件的 file_get_contents 返回 false
【发布时间】:2020-08-13 19:30:27
【问题描述】:

我试图 file_get_contents 一个 jpeg 文件,因为我需要它通过它的 REST API 将它上传到我的 Magento 站点。

$REMOTE_FILE_URL = "https://www.natures-collection.com/wp-content/uploads/2020/04/a389964a-dfba-48ad-81ba-09e639bc436a-450x450.jpg";

    $ax = file_get_contents($REMOTE_FILE_URL);
    $aa = base64_encode($ax);

    d($alld['image'], $REMOTE_FILE_URL, $ax, $aa);

    $basename = basename($alld['image']);
    $ext = explode(".",$basename)[1];

    if ($ext === "jpg") {

      $ext = "jpeg";
    }

    d($basename,$ext);
    $jso_aa = <<<EOT
    {
      "entry": {
        "media_type": "image",
        "label": "I am an image!",
        "types": [
          "image",
          "small_image",
            "thumbnail",
            "swatch"
        ],
        "content": {
            "base64_encoded_data": "$aa",
            "type": "image/{$ext}",
            "name": "{$basename}"

        },
        "file": "{$basename}"
      }
    }
EOT;
d($jso_aa);

    $reqq0 = <<<EOT
    curl -X POST "http://167.179.118.154/index.php/rest/default/V1/products/{$sku}/media" -H "Authorization: Bearer joax1huoa36e0b80thbx6zynmmrthnlq" -H "Content-Type:application/json" -d '{$jso_aa}'
EOT;

d() 是一个自定义函数,其作用类似于 var_dump()。

但是,file_get_contents 函数返回 false。当我转储 $ax 时,我看到 FALSE。

此 URL 会发生这种情况,它在浏览器上运行良好。

另一个像下面这样的 URL,没有这个问题: https://www.natures-collection.com/wp-content/uploads/2020/04/ea588379-eb43-4adb-a9d9-a3475ce7b2be.jpg

为什么会这样,我该如何解决?

【问题讨论】:

  • 这里工作正常。 imgur.com/a/SMWBSCY
  • 可能带有远程路径的 file_get_contents 已禁用,但显示错误消息已关闭。试着把ini_set("display_errors", 1); error_reporting(E_ALL|E_STRICT);

标签: php file-get-contents


【解决方案1】:

PHP 提示 file_get_contents() 被 403 禁止访问拒绝,所以我认为用户代理有问题。

演示:https://repl.it/@kallefrombosnia/filegetcon

$REMOTE_FILE_URL = "https://www.natures-collection.com/wp-content/uploads/2020/04/a389964a-dfba-48ad-81ba-09e639bc436a-450x450.jpg";

$options = [
    'http' => [
        'method' => 'GET',
        'header' => 'User-agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3219.0 Safari/537.36',   
    ]
]; 

$context = stream_context_create($options);

$ax = file_get_contents($REMOTE_FILE_URL, false, $context);

// just test that it actually works fine
file_put_contents('test.jpg', $ax);

// below is your code

【讨论】:

    猜你喜欢
    • 2022-01-02
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多