File upload and validation in php
In this post, we are going to show you how to File upload and validation in php. At first, we will create an HTML form in this form tag in pass an enctype=”multipart/form-data”. It specifies which content-type to use when submitting the form.
Create images folder on your project directory, when submitting a form at that time check validation, if that time validation true then an image will be inserted in the database and image will be uploaded in the images folder otherwise if any error then shows the error message.
See Below Example
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 44 45 46 | <?php if(isset($_POST['btnadd'])) { if(isset($_FILES)) { $file_name = $_FILES['imgFile']['name']; $file_size = $_FILES['imgFile']['size']; $file_tmp = $_FILES['imgFile']['tmp_name']; $file_type= $_FILES['imgFile']['type']; $acceptable = array('image/jpeg','image/jpg','image/png'); if(!in_array($file_type, $acceptable)) { $errors[]= "extension not allowed, please choose a JPEG or PNG file."; } else { include('connection.php'); $insert="insert into register (image) values('$file_name')"; mysql_query($conn,$insert); move_uploaded_file($file_tmp,"images/".$file_name); header('location:index.php?msg=Data Successfull Inserted'); } } } if(!empty($errors)) { echo '<script>alert("'.$errors[0].'");</script>'; } ?> <form method="post" enctype="multipart/form-data"> <table align="center"> <tr> <td colspan="2" align="center">Add Image</td> </tr> <tr> <td>Image</td> <td><input type="file" name="imgFile"> </td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="Add" name="btnadd"> </td> </tr> </table> </form> |
Please follow and like us: