Profile image upload in php

Live Image Upload using jQuery, PHP and MySQL

Live image upload feature makes web application more user-friendly. With live upload, the user can select and upload images without page refresh. Also, once the image is uploaded the preview shows the user which helps to update image without navigation to another page. You can implement live image upload feature with jQuery without using Ajax or any plugin.

The live image upload is very useful in user panel to update profile picture. In this tutorial, we will show the live image upload and user profile picture update functionality. You’ll learn how to upload and update image without page refresh using jQuery, PHP, and MySQL.

In our example script, we’ll fetch a particular user data from the MySQL database and show the user details on the web page. The user can change the profile picture without page refresh and their profile image will be updated in the database instantly.

Database Table Creation

Here the simple users table structure that holds the basic profile information.

CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `picture` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `modified` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

The dbConfig.php file is used to connect to the MySQL database using PHP. You have to specify the database host ( $dbHost ), username( $dbUsername ), password ( $dbPassword ), and name ( $dbName ).

//DB details
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'codexworld';

//Create connection and select DB
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

if(
$db->connect_error) die("Unable to connect database: " . $db->connect_error);
>

Live Image Upload (index.php)

Initially, the user’s name and the image will be displayed. Once the user moves the cursor over the profile picture, an edit icon will be shown. By the clicking on the edit icon, the user can select an image to update profile picture. The selected image will be uploaded to the server and profile picture name is updated in the database using the upload.php file. On completion of image upload, the profile picture will be replaced by the newly uploaded image and it will be shown to the user.

Читайте также:  Javascript if nested object

HTML & PHP Code:
The following HTML is used to display user’s name and image with update option.

//Include database configuration file
include_once 'dbConfig.php';

//Get current user ID from session
$userId = $_SESSION['user_id'];

//Get user data from database
$result = $db->query("SELECT * FROM users WHERE style="color: #0000BB">$userId");
$row = $result->fetch_assoc();

//User profile picture
$userPicture = !empty($row['picture'])?$row['picture']:'no-image.png';
$userPictureURL = 'uploads/images/'.$userPicture;
?> div class="container"> div class="user-box"> div class="img-relative"> div class="overlay uploadProcess" style="display: none;"> div class="overlay-content">img src="images/loading.gif"/>div> div> form method="post" action="upload.php" enctype="multipart/form-data" id="picUploadForm" target="uploadTarget"> input type="file" name="picture" id="fileInput" style="display:none"/> form> iframe id="uploadTarget" name="uploadTarget" src="#" style="width:0;height:0;border:0px solid #fff;">iframe> a class="editLink" href="javascript:void(0);">img src="images/edit.png"/>a> img src=" echo $userPictureURL; ?>" id="imagePreview"> div> div class="name"> h4> echo $row['name']; ?>h3> div> div> div>

JavaScript Code:
At first, include the jQuery library.

script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">script>

The following jQuery handles the image upload and update functionality.

script type="text/javascript"> $(document).ready(function () < //If image edit link is clicked $(".editLink").on('click', function(e)< e.preventDefault(); $("#fileInput:hidden").trigger('click'); >); //On select file to upload $("#fileInput").on('change', function()< var image = $('#fileInput').val(); var img_ex = /(\.jpg|\.jpeg|\.png|\.gif)$/i; //validate file type if(!img_ex.exec(image))< alert('Please upload only .jpg/.jpeg/.png/.gif file.'); $('#fileInput').val(''); return false; >else< $('.uploadProcess').show(); $('#uploadForm').hide(); $( "#picUploadForm" ).submit(); > >); >); //After completion of image upload process function completeUpload(success, fileName) < if(success == 1)< $('#imagePreview').attr("src", ""); $('#imagePreview').attr("src", fileName); $('#fileInput').attr("value", fileName); $('.uploadProcess').hide(); >else< $('.uploadProcess').hide(); alert('There was an error during file upload!'); > return true; > script>

Upload & Update Image (upload.php)

In the upload.php file, the image that posted from index.php file is uploaded to the server using PHP. Also, the existing profile picture name will update with the newly uploaded image name in the MySQL database using PHP. On completion of file upload, the completeUpload() function is loaded with status.

if(!empty($_FILES['picture']['name'])) //Include database configuration file 
include_once 'dbConfig.php';

//File uplaod configuration
$result = 0;
$uploadDir = "uploads/images/";
$fileName = time().'_'.basename($_FILES['picture']['name']);
$targetPath = $uploadDir. $fileName;

//Upload file to server
if(@move_uploaded_file($_FILES['picture']['tmp_name'], $targetPath)) //Get current user ID from session
$userId = 1;

//Update picture name in the database
$update = $db->query("UPDATE users SET picture = '".$fileName."' WHERE style="color: #0000BB">$userId");

//Update status
if($update) $result = 1;
>
>

//Load JavaScript function to show the upload status
echo ' ';
>

style.css

The following CSS are used in live image upload to look good.

.containerwidth: 100%;> .user-box < width: 200px; border-radius: 0 0 3px 3px; padding: 10px; position: relative; > .user-box .name < word-break: break-all; padding: 10px 10px 10px 10px; background: #EEEEEE; text-align: center; font-size: 20px; > .user-box formdisplay: inline;> .user-box .name h4margin: 0;> .user-box img#imagePreviewwidth: 100%;> .editLink < position:absolute; top:28px; right:10px; opacity:0; transition: all 0.3s ease-in-out 0s; -mox-transition: all 0.3s ease-in-out 0s; -webkit-transition: all 0.3s ease-in-out 0s; background:rgba(255,255,255,0.2) ; > .img-relative:hover .editLinkopacity:1;> .overlay< position: absolute; left: 0; top: 0; right: 0; bottom: 0; z-index: 2; background: rgba(255,255,255,0.7); > .overlay-content < position: absolute; transform: translateY(-50%); -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); top: 50%; left: 0; right: 0; text-align: center; color: #555; > .uploadProcess img< max-width: 207px; border: none; box-shadow: none; -webkit-border-radius: 0; display: inline; >

Conclusion

For demonstration purpose, we’ve used live image upload functionality for profile picture update. However, you can use this functionality to any kind of image upload or update. In jQuery code, the file type is validated before upload, presently it accepts only .jpg or .jpeg or .png or .gif file type. Add or remove the file extension as per your requirement.

Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request

If you have any questions about this script, submit it to our QA community — Ask Question

Источник

Uploading Profile Photo of a member

Members can add or update their photo to their membership account. This is popularly known as profile photo. We will learn how to add profile photo by a member.

Structure of Membership Table

This script is a part of membership management script so profile photo can be added or updated by the member after login. Here there is a membership table where all details of the member is stored. You can see the structure of the membership table here.

Watch the last column where we store the file name.

Unique file name

Each member profile photo is stored in a common folder so the file names are to be unique. Each member has one unique member id and user id. Hence we will store the file name along with the member id. For example for user id plus2net member id is 4. Hence the file name will be 4.jpg

You can add userid also to the file name. like plus2net.jpg

Where to store the profile pictures.

In the root of the script there is a folder profile-photo. Here we are uploading all images and storing profile photo. If you want to change the folder then it can be done inside memadmin area two different files used for uploading photo.

You must give write permission to this folder to enable file upload.

How members can add profile photo

Upload buttons for Profile picture

After login member can go to memadmin area saying settings. From memadmin area there are two links, one is to update profile and one more to update or add profile photo.

On visiting the profile photo page , the old profile photo page if already added will be displayed below the upload photo button. Here user can use the upload button to select a new profile photo from its computer. On Clicking the choose file button user can browse local computer files and select an image of JPG or GIF file type. Other file type are not allowed.

Once uploaded the file extension is checked for gif or jpg type images otherwise file is deleted.

After uploading the script check the dimensions of image and they are reduced proportionately to the required size.

$n_width=100; // Fix the width of the thumb nail images $n_height=100; // Fix the height of the thumb nail image

Once the resizing of images are over it is time to update the record with new file name. In our member table we store details of each member. For profile picture we have a column profile_photo. We will update this column with our new file name.

We will take member id which is unique and is present as session variable for updating record in where clause.

Here is the code for updating record with profile photo. Note that we are not storing the photo in the table but storing the file name against member record.

$sql=$dbo->prepare("update mem_signup set profile_photo=:profile_photo where mem_id=$_SESSION[mem_id] and userid='$_SESSION[userid]'"); $sql->bindParam(':profile_photo',$profile_file_name,PDO::PARAM_STR, 199); if($sql->execute())< echo "
Successfully updated Profile photo
"; echo ""; >// End of if profile is ok else< print_r($sql->errorInfo()); $msg="
Database problem, please contact site admin
"; >

How to check script or add profile photo

Download the script and install the database file. Inside Memadmin directory there are two files, profile-photo.php & profile-photock.php.
This is a part of Membership Management Script.

Script part

profile-photo.php

$profile_photo_path="../profile-photo/"; $count=$dbo->prepare("select profile_photo from mem_signup where mem_id=:mem_id"); $count->bindParam(":mem_id",$_SESSION['mem_id'],PDO::PARAM_INT,1); if($count->execute())< $row = $count->fetch(PDO::FETCH_OBJ); >else< print_r($dbo->errorInfo()); > echo "  "; if(strlen($row->profile_photo) > 1 )< // Path where thumb nail image will be stored $tsrc=$profile_photo_path.$row->profile_photo; echo ""; > ///////////////////////////// 

profile-photock.php

$profile_photo_path="../profile-photo/"; // To display file name, temp name and file type , //use them for testing your script only////// //echo "File Name: ".$_FILES['userfile']['name']."
"; //echo "tmp name: ".$_FILES['userfile']['tmp_name']."
"; //echo "File Type: ".$_FILES['userfile']['type']."
"; //echo "

"; /////////////////// // the path with the file name where the file will be stored. $add=$profile_photo_path.$_FILES['userfile']['name']; //echo $add; if(move_uploaded_file ($_FILES['userfile']['tmp_name'],$add))< //echo "
Successfully uploaded the image
"; chmod("$add",0777); >elseFailed to upload file Contact Site admin to fix the problem
"; @unlink($add); exit;> ///////////////////////// if (!($_FILES['userfile']['type'] =="image/jpeg" OR $_FILES['userfile']['type']=="image/gif"))< echo "
Your uploaded file must be of JPG or GIF. Other file types are not allowed"; unlink($add); exit;> ////////////////// ///////// Start the thumbnail generation////////////// $n_width=100; // Fix the width of the thumb nail images $n_height=100; // Fix the height of the thumb nail image if($_FILES['userfile']['type']=="image/gif") < $im=ImageCreateFromGIF($add); $width=ImageSx($im); // Original picture width is stored $height=ImageSy($im); // Original picture height is stored $newimage=imagecreatetruecolor($n_width,$n_height); imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height); $profile_file_name=$_SESSION['mem_id'].".gif"; // Path where thumb nail image will be stored $tsrc=$profile_photo_path.$profile_file_name; if (function_exists("imagegif")) < Header("Content-type: image/gif"); ImageGIF($newimage,$tsrc); >elseif (function_exists("imagejpeg")) < Header("Content-type: image/jpeg"); ImageJPEG($newimage,$tsrc); >chmod("$tsrc",0777); >////////// end of gif file thumb nail creation////////// ////////////// starting of JPG thumb nail creation////////// if($_FILES['userfile']['type']=="image/jpeg") < $im=ImageCreateFromJPEG($add); $width=ImageSx($im); // Original picture width is stored $height=ImageSy($im); // Original picture height is stored $newimage=imagecreatetruecolor($n_width,$n_height); imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height); $profile_file_name=$_SESSION['mem_id'].".jpg"; // Path where thumb nail image will be stored $tsrc=$profile_photo_path.$profile_file_name; ImageJpeg($newimage,$tsrc); chmod("$tsrc",0777); >$sql=$dbo->prepare("update mem_signup set profile_photo=:profile_photo where mem_id=$_SESSION[mem_id] and userid='$_SESSION[userid]'"); $sql->bindParam(':profile_photo',$profile_file_name,PDO::PARAM_STR, 199); if($sql->execute())< echo "
Successfully updated Profile photo
"; echo ""; >// End of if profile is ok else< print_r($sql->errorInfo()); $msg="
Database problem, please contact site admin
"; > unlink($add); echo $msg;

download Membership Management script

plus2net.com

Источник

Оцените статью