This blog Post concerns about Image uploading functionality using PHP and jQuery in forms. Just click on live demo or follow our codes to use it.
Here we have created an html form, set it’s attribute enctype=”multipart/form-data”. This form contains input tag , type=” file” when a user clicks on this input tag a window will opens for image file selection, after image selection an image preview is shown to user (using jquery). As user clicks on another input tag of type submit on which a PHP script will executes in which we wrote our codes in following steps:-
- We defined an array of allowed extensions .
$validextensions = array("jpeg", "jpg", "png");
- Defined a variable to store the selected file extension.
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
- Matching selected file size and it’s extension with allowed file size and allowed file extensions.
if ((($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/jpeg"))
&& ($_FILES["file"]["size"] < 100000)//approx. 100kb files can be uploaded
&& in_array($file_extension, $validextentions)){
//PHP Image Uploading Code
}
- If it is invalid file then,
echo "<span>***Invalid file Type or file Size Exceeded***<span>";
- Else the following code will execute:
echo "<span>Your File Uploaded Succesfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <b>already exists.</b> ";
}
else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "<b>Stored in:</b> " . "upload/" . $_FILES["file"]["name"];
}
-: See Also :-
Upload Multiple Images Using PHP and jQuery
HTML Form : upload.php
We have explained line by line process in the above section , Here we have Created a form with html syntax.
<!DOCTYPE html>
<html>
<head>
<title>Upload Image using form</title>
<link href="style.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div id="mainform">
<div id="innerdiv">
<h2>Upload Image using form</h2>
<!-- Required Div Starts Here -->
<div id="formdiv">
<h3>Upload Form</h3>
<form action="" enctype="multipart/form-data" id="form" method="post" name="form">
<div id="upload">
<input id="file" name="file" type="file">
</div>
<input id="submit" name="submit" type="submit" value="Upload">
</form>
<div id="detail">
<b>Note:</b>
<ul>
<li>To Choose file Click on folder.</li>
<li>You can upload- <b>images(jpeg,jpg,png).</b></li>
<li>Image should be less than 100kb in size.</li>
</ul>
</div>
</div>
<div id="clear"></div>
<div id="preview">
<img id="previewimg" src=""><img id="deleteimg" src="delete.png">
<span class="pre">IMAGE PREVIEW</span>
</div>
<div id="message">
<?php include 'uploadphp.php';?>
</div>
</div>
</div>
</body>
</html>
PHP Image Uploading Script : uploadphp.php
Here, We have given complete Image Uploading Script.
<?php
if (isset($_POST['submit'])) {
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 100000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
} else {
echo "<span>Your File Uploaded Succesfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <b>already exists.</b> ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
$imgFullpath = "http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"].'?').'/'. "upload/" . $_FILES["file"]["name"];
echo "<b>Stored in:</b><a href = '$imgFullpath' target='_blank'> " .$imgFullpath.'<a>';
}
}
} else {
echo "<span>***Invalid file Size or Type***<span>";
}
}
?>
jQuery Code: script.js
This, jquery code is to provide image preview facility in form, before Uploading it.
$(document).ready(function() {
// Function for Preview Image.
$(function() {
$(":file").change(function() {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$('#message').css("display", "none");
$('#preview').css("display", "block");
$('#previewimg').attr('src', e.target.result);
};
// Function for Deleting Preview Image.
$("#deleteimg").click(function() {
$('#preview').css("display", "none");
$('#file').val("");
});
// Function for Displaying Details of Uploaded Image.
$("#submit").click(function() {
$('#preview').css("display", "none");
$('#message').css("display", "block");
});
});
CSS File: style.css
Styling HTML Elements.
@import "http://fonts.googleapis.com/css?family=Droid+Sans";
/* Above is to load Google Fonts in our page.*/
#mainform{
width:960px;
margin:30px auto;
padding-top:20px;
font-family:'Droid Sans',sans-serif
}
#mainform h2{
margin-left:95px
}
#innerdiv{
float:left;
width:60%;
height:575px;
padding:10px 30px 30px
}
#formdiv{
background-color:#fff;
color:#123456;
box-shadow:0 1px 1px 1px gray;
width:480px;
margin:50px 0 0;
height:300px
}
h3{
margin-top:0;
color:#fff;
background-color:#1CC32B;
text-align:center;
width:100%;
height:50px;
padding-top:30px
}
input[type=submit]{
background-color:#1CC32B;
border:1px solid #fff;
font-weight:700;
font-size:18px;
color:#fff;
width:150px;
height:30px;
border-radius:3px;
padding:2px;
box-shadow:0 1px 1px 0 #a9a9a9;
margin-left:20px
}
#form{
width:43%;
float:left
}
#preview{
height:180px;
width:180px;
text-align:center;
margin:20px;
display:none
}
.pre{
margin-right:20px;
font-size:13px
}
#previewimg{
height:140px;
width:140px;
float:left;
padding:8px;
border:1px solid #e4d3c3;
margin-bottom:5px
}
#file{
opacity:0;
width:115px;
height:115px
}
#upload{
width:115px;
height:115px;
background-image:url(abc.png);
background-repeat:no-repeat;
margin-left:35px;
box-shadow:0 0 10px grey;
background-position:5px
}
#message{
width:100%;
font-size:14px;
color:#123456;
margin-top:-90px;
float:left;
margin:15px
}
#message span{
color:red;
font-size:15px
}
#detail{
line-height:20px;
float:left;
width:270px;
font-size:14px
}
ul{
margin-left:-25px
}
#textmessage{
float:right;
width:50%;
margin:15px 85px 0 0
}
div#img{
width:200px;
height:200px
}
#imageupload{
width:150px;
height:150px
}
#deleteimg{
cursor:pointer;
float:right;
margin-top:-175px;
margin-right:10px
}
Conclusion:
This was all about image uploading using PHP . Similarily, you can define other file extensions to upload them, just copy or download our codes to use it, keep following us for upcoming blogs.
18 Replies to “Upload Images Using PHP and jQuery via form”
This code doesn’t display the image after uploading
Hello Amna,
We sincerely apologize for this inconvenience. Now, we have updated our codes and it’s reference.
Always feel free to use FormGet in future too. Your suggestions & feedback will be always appreciated.
Thanks & Regards,
FormGet.com
it is very good code website plz update your code
I cant view the image after uploading
Image store in upload folder and image information displayed after run file. To show the image you just need to put
tag. and retrieve the image address.
What are the codes to show the image after uploading it?
hi… It was a good script
Thank you 🙂
how to get the Address of (upload) folder
Hello RajVerma,
we have updated our codes with( “getting full uploaded image address “) now you can use it
Always feel free to use FormGet in future too. Your suggestions & feedback will be always appreciated.
Thanks & Regards,
FormGet.com
Thanks for sharing this.
i was trying to upload image via jquery but form was not serialized to the file field.
Thanks again
Hi, great tutorial and scripts. Thanks a lot to share such valuable scripts. It is working perfectly. Thanks again.
thank indeed
You saved Me … THank U Very Much … awesome 🙂 🙂 😉 😉 😀 😀
How can i display entered image?
Also where is file stored after uploading on my server (in my case my localhost) ?
Thanks you.
Besssst.
Wow! is just that I need, it’s amazing thanks for sharing!
Hello,
What a great script, I am just wondering, how would we append a variable to the uploaded images name, to make sure the image is always unique, ie
$reg_id =”1234″;
so uploaded image would be image would be 1234_NameofImage.jpg
Thanks!
Image Uploaded Successfully but nothing in the folder.Why???