2016-03-28 120 views
0

好吧,我有一个简单的问题,我无法弄清楚 我怎样才能让PHP - 复制图像从另一个URL

$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变量使用$_GET[""]方法提交链接,而不必手动更改php文件中的链接?

+0

@ abrad1212,'$ image = file_get_contents($ _ GET ['url']);',但只有在清理完$ _GET ['url']'避免提交'?url = index.php'或类似人的问题 – Federkun

+0

如果图像较大,则会导致内存问题。 –

+0

看看这个:http://stackoverflow.com/questions/724391/saving-image-from-php-url – Andreas

回答

0

你已经像这样的形式:

<form> 
    URL: <input name="url"> 
    <input type="submit"> 
</form> 

然后你可以检索与$_GET['url']提交的网址:

$image = file_get_contents($_GET['url']); 
file_put_contents('/images/image.jpg', $image); 

无论如何,你一定要小心在本地文件包含,因为没有进一步的检查用户是否可以选择路径如/etc/passwd,../configuration.php等,如果/images/image.jpg可以由用户查看,他们可以读取不应该看到的文件。

你可能想要做的事情是检查$_GET['url]是否是一个有效的url。你可以这样做:

if (!filter_var($_GET['url'], FILTER_VALIDATE_URL)) { 
    throw new \InvalidArgumentException('The url is not valid.'); 
} 

但这还不够,因为file:///etc/passwd是一个有效的网址。所以,相反,只要确保网址以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 
} 
0

@Federico

First

Second

对不起,我没有很多时间来格式化我我的手机上载的一切到我的FTP服务器上的代码我在旅行 对不起,如果一切都局促

编辑:我看到了!在第二张照片上,删除它,所以不用担心

+0

不要提交答案,只需写评论。你有问题吗? – Federkun

+0

对不起,我对此有所了解,消毒工作正常,但图像根本无法保存,需要任何帮助 – abrad1212

+1

'/ images/image.jpg'是绝对路径。你可能想用'__DIR__替换它。 '/ images/image.jpg'' – Federkun

相关问题