使用PHP将图像保存来自URL

以下代码可从远程URL复制图像文件并使用PHP保存在文件夹中。

  • file_get_contents() - 此函数用于从URL读取图像文件并将内容返回为字符串。
  • file_put_contents() - 此函数用于将远程图像数据写入文件。
//Remote image URL
$url = 'http://www.example.com/remote-image.png';
//Image path
$img = 'images/onitroad.png';
//Save image 
file_put_contents($img, file_get_contents($url));

使用curl将图像从URL保存

我们可以使用CURL使用PHP将图像从URL保存。
以下代码可使用PHP中的curl从URL复制图像文件。

//Remote image URL
$url = 'http://www.example.com/remote-image.png';
//Image path
$img = 'images/onitroad.png';
//Save image
$ch = curl_init($url);
$fp = fopen($img, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
如何使用PHP从URL中保存图片

当我们希望从远程服务器动态复制图像并在本地服务器中存储时,从URL保存图像非常有用。
file_get_contents()和file_put_contents()提供了使用PHP将远程镜像保存到本地服务器的最简单方法。
图像文件可以直接保存到来自URL的目录。
在示例代码片段中,我们将提供两种方法可以使用PHP从URL中保存图像。

日期:2020-06-02 22:15:59 来源:oir作者:oir