In this tutorial, we will introduce the way to upload images to web server without refreshing web page using PHP and jQuery. jQuery will upload images and PHP will save images into disk and msyql.
1. Create index.php
You can upload images by this page.
<html lang="en"> <head> <title>Upload images using php and jquery whithout refreshing page</title> <!-- Bootstrap Css --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script> $(document).ready(function() { $(".upload-image").click(function(){ $(".form-horizontal").ajaxForm({target: '.preview'}).submit(); }); }); </script> </head> <body> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">PHP - Image Uploading with Form</a> </div> </div> </nav> <div class="container"> <form action="upload-image.php" enctype="multipart/form-data" class="form-horizontal" method="post"> <div class="preview"></div> <input type="file" name="image" class="form-control" style="width:30%" /> <button class="btn btn-primary upload-image">Save</button> </form> </div> </body> </html>
index.php will send image data to upload-image.php
2. Create db.php to connet mysql
We will connect mysql and insert image information.
<?php $servername='localhost'; $username='root'; $password=''; $dbname = "my_db"; $conn=mysqli_connect($servername,$username,$password,"$dbname"); if(!$conn){ die('Could not Connect MySql Server:' .mysql_error()); } ?>
2. Create upload-image.php to process uploaded image
We will save image and insert the image information into mysql.
<?php require_once "db.php"; if(isset($_POST) && !empty($_FILES['image']['name'])){ $name = $_FILES['image']['name']; list($txt, $ext) = explode(".", $name); $image_name = time().".".$ext; $tmp = $_FILES['image']['tmp_name']; if(move_uploaded_file($tmp, 'upload/'.$image_name)){ mysqli_query($conn,"INSERT INTO pictures (title) VALUES ('".$image_name."')"); echo "<img width='200px' src='upload/".$image_name."' class='preview'>"; }else{ echo "image uploading failed"; } } ?>