如何在PHP中验证URL上传的文件

如何在PHP中验证URL上传的文件

问题描述:

How to validate files before moving/uploading in the system.

I know how to validate file uploads in general, but I am looking for a solution about validating files that are uploaded by URL.

Here, have a look at my code, which refers to get the file and save it in my system :-

$file_url = 'https://www.something.com/images/Image.png'; // URL of the image/File
$destination_url = '/pictures/pics/image.jpeg';

// I have to assume that it's an image, and adding .jpeg since I don't know how to validate files without uploading it.

$data = file_get_contents($file_url); //gets the content of the file.
file_put_contents($destination_url, $data); //finally moves the file to system

And now I can do all the things, like getting it's name,size,type and so on, but that's not the point, Is there any way to validate the file before moving it to the system, since this procedure is really bad in security perspective, considering anyone can upload any size/type of file.


And before suggesting any library, please keep in mind I am using laravel framework.

如何在系统中移动/上传之前验证文件。 h2>

I 知道如何验证文件上传一般,但我正在寻找一个关于验证由URL上传的文件的解决方案。 p>

在这里,看看我的代码,它指的是获取 将文件保存到我的系统中: - p>

  $ file_url ='https://www.something.com/images/Image.png';  //图片的网址/文件
 $ destination_url ='/ picture /pics / image.jpeg'; 
  code> 
nnn

//我必须假设这是一个 图片,并添加.jpeg,因为 我不知道如何验证文件而不上传它。 p>

  $ data = file_get_contents($ file_url);  //获取文件的内容。
file_put_contents($ destination_url,$ data);  //最后将文件移动到system 
  code>  pre> 
 
 

现在我可以做所有的事情,比如获取它的名字,大小,类型和 所以,但这不是重点,有没有办法在将文件移动到系统之前验证文件,因为这个程序在安全性方面非常糟糕,考虑到任何人都可以上传任何大小/类型的文件。 p> \ n


在建议任何库之前,请记住我使用的是laravel框架。 p> div>

You can use get-headers() to obtain information such as content type and filesize before actually downloading the file contents.

To validate if the file is really what it says it is, e.g. to check that a .pdf file is not actually a .zip file in disguise, now that is a whole different story and I'm afraid there's no universal way to check that.

Use cURL to check for the file mime-type. http://php.net/manual/en/function.curl-getinfo.php