09
Nov
Upload image without refresh or post form in php
- Category:
- PHP
Posted On : November 9, 2013
| No Comment
We can upload file or image in php using jQuery. Here you can see image uploading by jQuery library. Even you can upload image as well video file, audio file ….etc
Step-1 : Look at following jQuery code and create index.php file as well add javascript code between <head> tag.
View Code JAVASCRIPT
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script> <script src="jquery.form.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { $('#photosrc').live('change', function() { $("#preview").html(''); $("#preview").html('<img src="loader.gif" alt="Uploading file now...."/>'); $("#formimage").ajaxForm( { target: '#preview' }).submit(); }); }); </script> |
Step-2 : Place following code into index.php file.
View Code PHP
include('database.php'); // Here database.php means database connection file session_start(); $session_id='1'; // User login session value ?> <form id="formimage" method="post" enctype="multipart/form-data" action='ajaximagefile.php'> Upload image <input type="file" name="photosrc" id="photosrc" /> </form> <div id='preview'> </div> |
Step-3: Lets create table into database
View Code MYSQL
CREATE TABLE `users` ( `userid` int(11) AUTO_INCREMENT PRIMARY KEY, `username` varchar(255) UNIQUE KEY, `password` varchar(100), `email_address` varchar(255) UNIQUE KEY, `profile_img` varchar(200), `profile_img_small` varchar(200), ) |
Step-4: Now create file in same folder name as ajaximagefile.php and place following code into file.
View Code PHP
include('database.php'); session_start(); $session_id='1'; // User session id $path = "uploaded_imgs/"; $valid_file_formats = array("jpg", "png", "gif", "bmp","jpeg"); if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") { $imgname = $_FILES['photosrc']['name']; $size_file = $_FILES['photosrc']['size']; if(strlen($imgname)) { list($txt, $extension) = explode(".", $ imgname); if(in_array($extension,$ valid_file_formats)) { if($size_file <(1024*1024)) // Image size should be max 1 MB { $actual_img_name = time().$session_id.".".$ext; $tmp = $_FILES['photosrc']['tmp_name']; if(move_uploaded_file($tmp, $path.$ actual_img_name)) { mysql_query("UPDATE users SET profile_img='$actual_img_name' WHERE uid='$session_id'"); echo "<img src='uploaded_imgs/".$actual_img_name."' class='preview'>"; } else echo "Upload failed"; } else echo "Image file size should be max 1 MB"; } else echo "Invalid image file format."; } else echo "Error ! Please select any image..!"; exit; } |
- Tags: