Upload image in PHP:
Upload image in PHP : insert image value into the database and upload image in a folder using PHP programming language.
When you insert some user details and you want insert user photo or ID details picture then you can upload the image file into MySQL table with upload image into destination folder.
PHP website you can image into database using MySQLi query. It is easy process and I will show you different type of uploading image into database in PHP.
What you do for upload image or file into database, first you have to need a form and get a file field into the Form. I mean that get type=”file” attribute of the <input> tag. Then the next work is to set POST method in the Form, because POST if perfectly get the file value form the file field, POST method is need to set in Form.
You must set file upload attribute in the form without file upload attribute you can’t upload file into database or directory. So following attribute: enctype=”multipart/form-data”. Now follow the example and source codes:
Create Form:
<form method="post" enctype="multipart/form-data"> <div class="form-group"> <label> Upload Image </label> <div> <input type="file" name="image_file" id="blog_file" /> </div> <div> <button type="submit" name="submit">Upload Image</button> </div> </div> </form>
PHP Upload Image:
<?php if(isset($_POST['upload'])) { $filename =$_FILES["image_file"]["name"]; move_uploaded_file($_FILES['image_file']['tmp_name'],'uploads/images/'.$filename); $sql=mysqli_query($con,"insert into `Table Name` (`image_file`) values ('".$filename."')"); } ?>
If you want to set the time() function when uploading file into Database. The time() function is get the time of your system and store the time in your file value. It will help you, when user upload same type of image file and which name is same. That’s like:
<?php if(isset($_POST['upload'])) { $filename = time() .$_FILES["image_file"]["name"]; move_uploaded_file($_FILES['image_file']['tmp_name'],'uploads/images/'.$filename); $sql=mysqli_query($con,"insert into `Table Name` (`image_file`) values ('".$filename."')"); } ?>
If you want to upload image into the database to choosing extension name. So upload image file with the particular extension or check this is the particular image file. So get the extension name of image file when you uploading then check and set a message for it. Follow the code:
<?php if(isset($_POST['upload'])) { $fileUpload=$_FILES["image_file"]["name"]; $extention=pathinfo($fileUpload,PATHINFO_EXTENSION); if($extention != "jpg" && $extention != "png" && $extention != "jpeg" && $extention != "gif"){ echo "Please give a apropiate image"; }else{ $filename =$_FILES["image_file"]["name"]; move_uploaded_file($_FILES['image_file']['tmp_name'],'uploads/images/'.$filename); $sql=mysqli_query($con,"insert into `Table Name` (`image_file`) values ('".$filename."')"); } ?>
Awesome tutorial. It’s totally the best I’ve ever seen. Thanks.