Reputation: 5262
In order to have a safe upload page. we need to prevent uploading any executable file like: php
, asp
using something like this:
<Files *.php>
Deny from All
</Files>
But what if someone tries to upload a .htaccess
file?
How can prevent uploading .htaccess
files in htaccess?
EDIT
anyone can change headers to upload a php
file or asp
or whatever, including .htaccess
well, this is a good looking and secure code:
$extension = pathinfo($_FILE['file']);
$valid = ['jpg','png','gif'];
if(in_array($extension,$valid))
// ok. upload file
else
// something is wrong.
but I can rename a php
file to a test.jpg
file and upload it, it's a valid jpg file and my script will allow it to upload, now, I change headers and change test.jpg
to test.php
file, and assume this test.php file is a shell file.... .
Upvotes: 0
Views: 3412
Reputation: 6480
Your question should be (How to validate an image)
This is one of the functions of exif_imagetype()
exif_imagetype — Determine the type of an image
And then compare the what that function will return to you as a type of the image with your white list images types.
When a correct signature is found, the appropriate constant value will be returned otherwise the return value is FALSE. The return value is the same value that getimagesize() returns in index 2 but exif_imagetype() is much faster.
Sample usage:
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
echo 'The picture is not a gif';
}
If you would like to allow multiple types, then include them into an array and check if the retured type exists in that array.
Another solution would be to use getimagesize()
which returns zeros for size on non-images.
Aside note: have all images uploaded into a separate sub directory rather than a directory that contains some php files or any other code files.
Update:
Based on your comment. If you want to allow the user to upload whatever kinds of files they wish to [not only images], then validating against all kind of files would seem endless. Therefore if I were to do that, I would mask the file and make it not executable. But if you have a set of allowed files to be uploaded, then I recommend you list it somewhere and validate against it.
1.Method 1: rename the file and/or change it's extension to something else.
The server is configured only to execute a set of known types of files.
If the user choose to upload file.php
then save that file name into the db, and rename the actual file's name to file_[timestamp][user_id][randome_code]
for example and save the new name to the db as well. And then whenever the user requests that file, just rename it to it's original name and allow him/her to download.
2.Method 2: compress the file into .zip. It won't be executable able that way.
Upvotes: 1