首页  >  文章  >  后端开发  >  如何使用 PHP 使用 Copy 或 file_get_contents 将图像从 URL 下载并保存到服务器?

如何使用 PHP 使用 Copy 或 file_get_contents 将图像从 URL 下载并保存到服务器?

Patricia Arquette
Patricia Arquette原创
2024-10-18 22:55:30175浏览

How to Download and Save an Image from a URL to Server with PHP using Copy or file_get_contents?

使用 PHP 将图像从 URL 复制到服务器

问题:

如何创建PHP代码从指定URL下载图像并直接保存在我的服务器上,权限为777?

答案:

选项1(PHP5或更高版本) ):

使用 copy() 函数:

<code class="php">copy('http://www.google.co.in/intl/en_com/images/srpr/logo1w.png', '/tmp/file.png');</code>

选项 2(PHP4 及以下):

使用 file_get_contents( ) 检索图像并使用 fopen() 和 fwrite() 保存图像:

<code class="php">// Get the image
$content = file_get_contents("http://www.google.co.in/intl/en_com/images/srpr/logo1w.png");

// Save the image
$fp = fopen("/location/to/save/image.png", "w");
fwrite($fp, $content);
fclose($fp);</code>

注意: 要对下载的图像设置 777 权限,请在之后使用 chmod() 函数下载:

<code class="php">chmod("/tmp/file.png", 0777); // or chmod("/location/to/save/image.png", 0777)</code>

以上是如何使用 PHP 使用 Copy 或 file_get_contents 将图像从 URL 下载并保存到服务器?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn