简体   繁体   中英

How to prevent php from uploading files:

How do you prevent php from uploading files into./tmp/ folder if they are not the correct type.

For example the sample code given on the w3school website checks the file length using the following code:

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))

But this is after the files have already been uploaded to temp, am I correct? Is there any way to do this in php or will I have to do it on the client side?

PHP cannot know the type of the file before it was uploaded to the server so PHP could get its hands on it. For that purpose the file will need to be stored in a temp folder. Also, PHP will do no checking for you, you will have to check in your script (for which purpose the file needs to be saved somewhere).

To prevent uploads of invalid files, you'd need to check client side. This often involves Flash or other plugins, since Javascript is sandboxed and can't access files on the harddisk (search for exceptions to this rule on this very site).

Any client side validation is pointless though, since it's client side , your server cannot trust client information. For that matter, the $_FILES['file']['type'] information is entirely client-provided information as well, which you should not trust. Check the MIME type of a file yourself to verify. For examples on how to do this, see How to get the content-type of a file in PHP?

I dont think this is possible to do either in client side or in server side. The file upload will upload to a temporary directory and thats where you parse it.

As others have said, you can't access the filetype until the file is uploaded. Assuming this is for 'user experience' purposes (and not security purposes), you can use javascript to check the file name and look at its extension:

document.getElementById("file-input").file

will return the filename, and you can parse everything after the '.'to see if it's a gif, jpg, etc. Obviously, this extension is just a container (and might even be mislabeled by a malicious user), and is not a 'true' filetype.

If you really want to do it in PHP, you can have a javascript that passes the name value as a hidden input in the form, and your PHP can stop by the file upload based on this value. But it would make a lot more sense to do this in Javascript since, again, this isn't a security measure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM