In this post, I’m going to show you how to upload and validate files using 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

<?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>

Connect With Facebook