Upload and Validate an Image in PHP
In this tutorial I will explain how to upload a image and how to validate image extension
Create a HTML form with two text field :
- One is for Image title with input type text.
- Second one is for upload image with input type file.For file upload input must be file(type=”file”). This input type show the file select control.
HTML form must have following attributes :
- method=”post”
- enctype=”multipart/form-data” (The enctype attribute specifies how the form-data should be encoded when submitting it to the server.)
without these attributes , the image upload will not work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<form name="uploadimage" enctype="multipart/form-data" method="post"> <table width="100%" border="0"> <tr> <th width="26%" height="60" scope="row">Image Title:</th> <td width="74%"><input type="text" name="imagetitle" autocomplete="off" class="form-control" required /></td> </tr> <tr> <th height="60" scope="row">Upload Image :</th> <td><input type="file" name="image" required /></td> </tr> <tr> <th height="60" scope="row"> </th> <td><input type="submit" value="Submit" name="submit" class="btn-primary" /></td> </tr> </table> </form> |
Create a database with name imagesdata. Inside this database we create a table with name tblimages.
SQL Script for tblimages
1 2 3 4 5 6 |
CREATE TABLE IF NOT EXISTS `tblimages` ( `id` int(11) NOT NULL, `ImagesTitle` varchar(120) DEFAULT NULL, `Image` varchar(150) DEFAULT NULL, `PostingDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1; |
Now create a database connection file(config.php)
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php define('DB_SERVER','localhost'); define('DB_USER','root'); define('DB_PASS' ,''); define('DB_NAME', 'imagesdata'); $con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } ?> |
PHP Script for getting posted values, image validation, move images into directory and insertion data into database
It is great how you made a complex issue sound so simple, thank you so so much.
Good advice. I still see people not validating file types, which can, of course, have security implications.
Thank you for the simple explanation.. daily I learn something new from your blog. Thank you so much .
am glad you are grabbing something.
Thanks for sharing this wonderful blog post. It is so helpful and easy to understand.
I need to learn more about this, codes for me are a little too much
determination is all you need.
I loved how you explained step by step process of validating an image. I feel like every day I learn something new through my blog!
Thanks Ann