Howdy coders,
In this post, I’m going to show you how to upload and validate files using PHP. At first we’ll need a simple HTML form with an input type=”file”, then we’ll catch the uploaded file from PHP using $_FILES[“file”]. Then we’ll validate it by extension, mime-type and file size; then process it further.
Our validation condition will be as below:
- Allowed file type: Word processing / Document files and pdf files
- Allowed extensions: doc, docx, odt and pdf
- Allowed file size: less than 100 kB
<html> <head> <title>Upload & Validate files using PHP - W3Epic.com</title> </head> <body> <?php $error = ""; if (isset($_FILES["file"])) { $allowedExts = array("doc", "docx", "pdf", "odt"); $temp = explode(".", $_FILES["file"]["name"]); $extension = end($temp); if ($_FILES["file"]["error"] > 0) { $error .= "Error opening the file<br />"; } if ( $_FILES["file"]["type"] != "application/pdf" && $_FILES["file"]["type"] != "application/vnd.openxmlformats-officedocument.wordprocessingml.document" && $_FILES["file"]["type"] != "application/msword" && $_FILES["file"]["type"] != "application/vnd.oasis.opendocument.text") { $error .= "Mime type not allowed<br />"; } if (!in_array($extension, $allowedExts)) { $error .= "Extension not allowed<br />"; } if ($_FILES["file"]["size"] > 102400) { $error .= "File size shoud be less than 100 kB<br />"; } if ($error == "") { echo "uploaded successfully"; } else { echo $error; } } ?> <form action="upload.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /><br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html>
I hope its useful for you.
For other data fields server side validation using PHP, see this post.
If you need any help, just leave a comment.
Thank you!
Where is the part that actually uploads the file into the database?
We’re not uploading file into database but on the disk as file. But you can keep the file information in the database.
Yes but where is code to save file on disk ?
making fool
This it’s not working
thanks for the code.. helped me 🙂 I wish i could donate you guys but i am not from a high standard country and family too..,, so, sry n Someday may be i will ..
how to check the real file? not only the extension? If only extension check, there a lot article out there and your post seen only copy paste….. useless!!!
I really like your post. I check out your website fairly regularly, and you are constantly
coming up with some decent staff. I shared this post on my Facebook, and my followers liked it!
Good luck.