PHP-从另一个URL复制图像
好吧,我有一个简单的问题,我想不出来 我该怎么做PHP-从另一个URL复制图像,php,Php,好吧,我有一个简单的问题,我想不出来 我该怎么做 $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 我可以使用html表单设置$image变量,人们可以使用$\u GET[“”]方法提交链接,而不必手动更改php文件中的链接?您有这样一个表单: &l
$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
我可以使用html表单设置
$image
变量,人们可以使用$\u GET[“”]
方法提交链接,而不必手动更改php文件中的链接?您有这样一个表单:
<form>
URL: <input name="url">
<input type="submit">
</form>
无论如何,您必须小心本地文件包含,因为用户无需进一步检查即可选择路径,如
/etc/passwd
、./configuration.php
等,如果用户可以查看/images/image.jpg
,则可以读取不应该看到的文件
您可能需要做的一件事是检查$\u GET['url
]`是否是有效的url。您可以通过以下方式实现:
if (!filter_var($_GET['url'], FILTER_VALIDATE_URL)) {
throw new \InvalidArgumentException('The url is not valid.');
}
但这还不够,因为file:///etc/passwd
是一个有效的url。因此,只需确保url以http://
或https://
开头即可
$isValid = false;
foreach(['http://', 'https://'] as $schema) {
if (strpos($_GET['url'], $schema) === 0) {
$isValid = true;
break;
}
}
if ($isValid && filter_var($_GET['url'], FILTER_VALIDATE_URL)) {
$image = file_get_contents($_GET['url']);
file_put_contents('/images/image.jpg', $image); //Where to save the image on your server
}
@费德里科
对不起,我没有太多时间来格式化代码。我在手机上,在旅行时将所有内容上传到FTP服务器
很抱歉,如果一切都很拥挤
编辑:我看到了!在第二张图片上删除了它,所以不用担心@abrad1212,
$image=file\u get\u contents($\u get['url')
,但只有在你清理了$\u GET['url']
之后,才能避免提交?url=index.php
或类似文件的人出现问题。如果图像较大,它将导致内存问题。请看一下:@Federico你对清理$\u GET[“url”]的意思是什么?你能给我举个例子吗,我认为您不希望人们选择。/../../../etc/passwd
作为url。也许您需要检查url是否总是以http(s)开头://不要提交答案,只需写评论即可。你有什么问题吗?抱歉,我是新来的,消毒工作正常,但图像根本没有保存,需要任何帮助/images/image.jpg
是绝对路径。您可能需要将其替换为\uuuuuu DIR\uuuuuuuu.'/images/image.jpg'
您可能没有/images/
中的写入权限。启用php错误,将错误报告(-1);ini设置(“显示错误”,真)
在file.change的顶部文件内容(\uuuuu DIR\uuuu.'/imgs/,$image)
tofile\u put\u内容(\uu DIR\uu.'/imgs/somefilename.jpg',$image)代码>
$isValid = false;
foreach(['http://', 'https://'] as $schema) {
if (strpos($_GET['url'], $schema) === 0) {
$isValid = true;
break;
}
}
if ($isValid && filter_var($_GET['url'], FILTER_VALIDATE_URL)) {
$image = file_get_contents($_GET['url']);
file_put_contents('/images/image.jpg', $image); //Where to save the image on your server
}