Hello Friends, today we’ll see malicious file upload prevention in PHP. If in our web application there is file upload feature then we should add this feature with precautions because this is a very easy way for any attacker to inject malicious code in our application. So here is the code
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<?php $msg = ""; if (isset($_FILES['file']) && $_FILES['file']['error'] != 4) { $msg = "<b>Choosen: " . $_FILES['file']['name'] . "</b>"; $fileSize = $_FILES["file"]["size"]; $fileExtension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); //$fileType = $_FILES["file"]["type"];//this can be easily modified by attacker $fileType = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $_FILES['file']['tmp_name']); $allowedFileSize = 10000000 * 2; //2MB $allowedExtentions = array("pdf", "doc", "docx", "jpeg", "jpg", "png"); $allowedFileTypes = array("application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "image/jpeg", "image/jpg", "image/png",); if ($fileSize > $allowedFileSize) { //checking file size $msg .= "<p>Maximum 2MB Allowed</p>"; } else if (!in_array($fileExtension, $allowedExtentions) || !in_array($fileType, $allowedFileTypes)) { //checking file extension and type $msg .= "<p>Only pdf, doc, docx, jpg and png files are allowed.</p>"; } else { if (!file_exists("uploads")) { //checking if uploads folder exists mkdir("uploads", 0777, true); } if (move_uploaded_file($_FILES['file']['tmp_name'], "uploads/" . $_FILES['file']['name'])) { //saving file $msg .= "<p>File Uploaded Successfully!</p>"; } else { $msg .= "<p>Error! While Saving File</p>"; } } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Malicious File Upload Prevention</title> </head> <body bgcolor="silver"> <form method="post" enctype="multipart/form-data"> <input type="file" name="file"/> <input type="submit" value="Upload"/> </form> <?= $msg ?> </body> </html> |
Output
Download Code
Malicious File Upload Prevention in PHP
1 file(s) 423.08 KB
Thanks for visiting
Please do share if you liked
Comments