使用 php 将远程 img 文件保存到服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1371966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:14:36  来源:igfitidea点击:

Save remote img-file to server, with php

phpsave

提问by Johan

I want to save a remote img-file to my server, but I don't know how to do.

我想将远程 img 文件保存到我的服务器,但我不知道该怎么做。

The image url is http://img.youtube.com/vi/Rz8KW4Tveps/1.jpgand 1.jpgis to be saved and renamed to imgfolder/imgID.jpg

图片网址是http://img.youtube.com/vi/Rz8KW4Tveps/1.jpg1.jpg要保存并重新命名为imgfolder/imgID.jpg

回答by Guss

You can use file_get_contents()to load the remote image to a binary string inside your PHP script (file access in PHP often accepts URLs to access remote resources - this is very handy), then store that file somewhere where you have write access. Here is a very simple example:

您可以使用file_get_contents()将远程图像加载到 PHP 脚本中的二进制字符串(PHP 中的文件访问通常接受 URL 来访问远程资源 - 这非常方便),然后将该文件存储在您具有写访问权限的地方。这是一个非常简单的例子:

$image = file_get_contents("http://img.youtube.com/vi/Rz8KW4Tveps/1.jpg");
file_put_contents("imgfolder/imgID.jpg", $image);

Tada!

多田!

回答by Ciaran McNulty

If the URL stream wrappers are allowed, you can do it in 1 line rather than having to load it into a var:

如果允许使用 URL 流包装器,则可以在 1 行中完成,而不必将其加载到 var 中:

copy('http://img.youtube.com/vi/Rz8KW4Tveps/1.jpg', 'imgfolder/imgID.jpg');

This is much less likely to cause a problem with PHP running out of memory.

这不太可能导致 PHP 内存不足的问题。