File uploader is always a point for a hacker where he/she can hack your website by uploading a malicious script file on your server if you do not have put the proper validation into the server side code.
If a hacker is able to upload his script on to your server then he can easily access all the files and database on to your server. So always have a proper file type validation on the server side.
2 important file validation checks on server side
1) Checking the extension of the file
2) Checking the content type of the file
Checking the extension of the file
Always check the extension of the file before saving to the server. If only image type files are allowed then check the extension of the file for “.jpg, .png, .gif, .jpeg” only. If the file have any other extension then remove it immediately from the temporary directory.
You can get the extension of the file through the function pathinfo()
$fileInfo = pathinfo( $filePath );
$extension = $fileInfo["extension"];
Checking the content type of the file
Many web developer thinks that file extension checking is enough while making a file uploader on a website to prevent malicious file upload and they can stop hackers. But that’s not at all true. As we can upload a .php file by changing it’s extension to .jpeg. Hackers can easily change the extension of the file to .php after it has been uploaded. SO now they can do anything with your server as their script is running on your server.
How to stop it?
To stop this, check the content type of the file before saving the uploaded file to the server.
Php have a special function called mime_content_type() which provides the content type of the file.
$content_type = mime_content_type($file_path);
This function will return “image/jpeg” for a jpeg image, “image/png” for a png image and so on.