【问题标题】:Saving a remote image programmatically with PHP使用 PHP 以编程方式保存远程图像
【发布时间】:2018-05-16 15:22:19
【问题描述】:

我正在尝试将一些内容从一种资源迁移到另一种资源中,并且需要保存一些位于远程资源中的图像(数百张)。

假设我只有一张图片的 URL:

https://www.example.com/some_image.jpg

我想使用 PHP 将它保存到文件系统中。

如果我要上传图片,我基本上会执行以下操作:

<input type="file" name="my_image" />

move_uploaded_file($_FILES['my_image']['tmp_name'], '/my_img_directory');

但由于我只有 URL,所以我想像这样:

$img = 'https://www.example.com/some_image.jpg';
$file = readfile($img);
move_uploaded_file($file, '/my_img_directory');

这当然行不通,因为move_uploaded_file() 没有将输出缓冲区作为第一个参数。

基本上,在这种方法下,我需要将$img 放入$_FILES[] 数组中。或者可能有其他方法?

【问题讨论】:

    标签: php image upload readfile output-buffering


    【解决方案1】:

    您可以使用 PHP 的复制功能将远程文件复制到您服务器上的某个位置:

    copy("https://example.com/some_image.jpg", "/path/to/file.jpg");
    

    http://php.net/manual/en/function.copy.php

    【讨论】:

      【解决方案2】:
      $image = file_get_contents('http://www.url.com/image.jpg');
      file_put_contents('/images/image.jpg', $image); //Where to save the image on your server
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-21
        • 1970-01-01
        • 1970-01-01
        • 2021-01-02
        • 2019-04-16
        • 1970-01-01
        相关资源
        最近更新 更多