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

Patricia Arquette
发布: 2024-10-18 22:55:30
原创
172 人浏览过

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中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!