Not long ago, a visitor was asking how to upload an image in PHP on AdminLTE Framework. He asked how to upload and save images to a MySQL database with Blob data type. Storing images into the MYSQL database is not the right way in my opinion as it will make the database capacity to be large, but maybe he needs it for a particular app.
Read another article : Simple CRUD Apps With Codeigniter Tutorial For Beginners
Actually to look for PHP tutorial how to upload images have been discussed by many big sites that you can find on google search engine. I am trying to explain as much as I can, how to upload images with PHP and JQuery. For this article will explain how to upload images PHP in 3 ways:
- Upload images manually using PHP and Javascript
- Upload an image using cropbox.js.
- Upload an image using the jQuery File Upload Plugin
The three ways above are equally easy, and please choose your own that suits your application to apply to adminLTE Framework
Table of Contents
PHP tutorial how to upload image using PHP and Jquery
As a preparation tutorial, please download adminLTE Framework first here. Then create a MySQL database with the name “testupload.” Add a “pos” table and a field with the name “image” type BLOB like the picture below.
Extract adminLTE source code and rename the folder to “uploadimages.”. Create new folder “application” in folder “uploadimages/“. Create new folder “upload” in folder “uploadimages/application/“
If the above preparations have been completed, let’s start from the first way first
# Upload images manually using PHP and Javascript
- Copy the blank.html file in
“uploadimages/pages/examples/” folder to “uploadimages/application/upload/” folder and rename it to upload1.html. - Find the code
<div class="box-body">
and add the following script under the code:12345678<input type="file" id="file" onchange='openFile(event)' style="float:left; width: 250px"><input type="hidden" id="image"><br><br><button id="clicktest" class="btn btn-default">Test Upload</button><br><br><img id="myimage" src=""/> - Add the following javascript code:123456789101112131415161718192021222324252627282930var openFile = function(event) {var openFile = function(event) {var input = event.target;var reader = new FileReader();reader.onload = function(){document.getElementById('image').value = reader.result;};reader.readAsDataURL(input.files[0]);};$("#clicktest").click(function(){var value = {img : window.btoa($("#image").val()),}$.ajax({url : "ajax1.php",type: "POST",data : value,success: function(data, textStatus, jqXHR){var data = jQuery.parseJSON(data);$("#myimage").attr("src",' data : image/jpeg ; base64,'+data.img);},error: function(jqXHR, textStatus, errorThrown){}});})
Explanation:
To upload a file or image javascript requires the FileReader() class to process the image. For more details, please visit javascripture for more information. - Create a new PHP file with the name ajax1.php in the
“uploadimages/application/upload/” folder and copy the following code1<!--?php $data=base64_decode($_ POST['img']); list($type, $data) = explode(';', $data); list(, $data) = explode(',', $data); $typedata = explode("/", $type); $type = $typedata[1]; // upload image to folder $xdata = base64_decode($data); file_put_contents('new_image.'.$type, $xdata); /********mysql connection*****/ $host="localhost"; $user="root"; $pwd=""; $dbname="testupload"; $link=mysql_connect($host,$user,$pwd); $db = mysql_select_db($dbname,$link); if(!$db) echo mysql_error(); // insert into database mysql_query('insert into pos(image) values("'.$data.'")'); //*******************// $array = array(); $array['img'] = $data; echo json_encode($array); ?-->
Please test the result in your browser with the following url
http: //localhost/uploadimages/application/upload/upload1.php
If successful, then the application will run like the following picture.
# PHP Tutorial Upload images using cropbox.js.
The advantage of using the cropbox.js plugin is cropbox.js has a feature to crop images, often used to create apps that will display thumbnail images.
- Download the cropbox.js plugin here https://github.com/hongkhanh/cropbox.
- Place the cropbox.js file in the “uploadimages/dist/js/” folder
- Copy the blank.html file in folder
“uploadimages/pages/examples/” to “uploadimages/application/upload/” folder and change its name to upload2.html - Copy the following css script1234567891011121314151617181920212223242526272829303132333435363738394041424344454647.imageBox{position: relative;height: 400px;width: 400px;border:1px solid #aaa;background: #fff;overflow: hidden;background-repeat: no-repeat;cursor:move;}.imageBox .thumbBox{position: absolute;top: 50%;left: 50%;width: 200px;height: 200px;margin-top: -100px;margin-left: -100px;border: 1px solid rgb(102, 102, 102);box-shadow: 0 0 0 1000px rgba(0, 0, 0, 0.5);background: none repeat scroll 0% 0% transparent;}.imageBox .spinner{position: absolute;top: 0;left: 0;bottom: 0;right: 0;text-align: center;line-height: 400px;background: rgba(0,0,0,0.7);}.action{width: 400px;height: 30px;margin: 10px 0;}.cropped>img{margin-right: 10px;}
- Find the code “<div class=”box-body”>” and add the following script under the code12345678910111213141516<div class="container"><div class="imageBox"><div class="thumbBox"></div><div class="spinner" style="display: none">Loading...</div></div><div class="action"><input type="file" id="file" style="float:left; width: 250px"><input type="button" id="btnCrop" value="Crop" style="float: right"><input type="button" id="btnZoomIn" value="+" style="float: right"><input type="button" id="btnZoomOut" value="-" style="float: right"></div><div class="cropped"></div><img id="myimage" src=""/></div>
- Add the following javascript code123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051$(window).load(function() {var options ={thumbBox: '.thumbBox',spinner: '.spinner',imgSrc: 'avatar.png'}var cropper = $('.imageBox').cropbox(options);$('#file').on('change', function(){var reader = new FileReader();reader.onload = function(e) {options.imgSrc = e.target.result;cropper = $('.imageBox').cropbox(options);}reader.readAsDataURL(this.files[0]);})$('#btnCrop').on('click', function(){var img = cropper.getDataURL();$('.cropped').html("");$('.cropped').append('<img class="display:block" id="images" src="'+img+'"><br><button id="saveimage" class="btn btn-default">Save Image</button><br><br>');})$('#btnZoomIn').on('click', function(){cropper.zoomIn();})$('#btnZoomOut').on('click', function(){cropper.zoomOut();})});$(document).on("click","#saveimage",function(){var value = {img : window.btoa($("#images").attr("src")),}$.ajax({url : "ajax1.php",type: "POST",data : value,success: function(data, textStatus, jqXHR){var data = jQuery.parseJSON(data);$("#myimage").attr("src","data : image/jpeg ; base64,"+data.img);},error: function(jqXHR, textStatus, errorThrown){}});})
Run the app in the browser using the URL as follows:
“HTTP: //localhost/uploadimages/application/upload/upload2.php“.
If successful, then the application will run like the following picture.
# PHP Tutorial Upload an image using the “jQuery File Upload” Plugin
“JQuery File Upload” is a very nice jquery plugin and the view fits perfectly with the adminLTE framework. Also, the use of this plugin is also effortless.
- Download the jquery file plugin uploaded here
- extract file jQuery-File-Upload-9.18.0.zip.
- copy all files in “js” folder in “jQuery-File-Upload-9.18.0” to folder
“uploadimages/dist/js/ jqueryupload/“ - Copy the file “jquery.fileupload.css” in the folder “uploadimages/dist/css/“
- Copy the “server” folder in
“jQuery-File-Upload-9.18.0” folder into the “uploadimages/application/upload/upload” folder - Copy the blank.html file in
“uploadimages/pages/examples/” folder to “uploadimages/application/upload/” folder and rename it to upload3.html.
Add a script to invoke the following “jquery.fileupload.css” above </ head>1<link rel="stylesheet" href="../../dist/css/jquery.fileupload.css">
Add a script to call the Jquery plugin with the following code123456789101112131415161718<script src="../../dist/js/jqueryupload/vendor/jquery.ui.widget.js"></script><script src="//blueimp.github.io/JavaScript-Load-Image/js/load-image.all.min.js"></script><!-- The Canvas to Blob plugin is included for image resizing functionality --><script src="//blueimp.github.io/JavaScript-Canvas-to-Blob/js/canvas-to-blob.min.js"></script><!-- The Iframe Transport is required for browsers without support for XHR file uploads --><script src="../../dist/js/jqueryupload/jquery.iframe-transport.js"></script><!-- The basic File Upload plugin --><script src="../../dist/js/jqueryupload/jquery.fileupload.js"></script><!-- The File Upload processing plugin --><script src="../../dist/js/jqueryupload/jquery.fileupload-process.js"></script><!-- The File Upload image preview & resize plugin --><script src="../../dist/js/jqueryupload/jquery.fileupload-image.js"></script><!-- The File Upload audio preview plugin --><script src="../../dist/js/jqueryupload/jquery.fileupload-audio.js"></script><!-- The File Upload video preview plugin --><script src="../../dist/js/jqueryupload/jquery.fileupload-video.js"></script><!-- The File Upload validation plugin --><script src="../../dist/js/jqueryupload/jquery.fileupload-validate.js"></script> - Find the code
<div class="box-body">
and add the following html script under the code
123456789101112131415<span class="btn btn-success fileinput-button"><i class="glyphicon glyphicon-plus"></i><span>Add files...</span><!-- The file input field used as target for the file upload widget --><input id="fileupload" type="file" name="files[]" multiple></span><br><br><!-- The global progress bar --><div id="progress" class="progress"><div class="progress-bar progress-bar-success"></div></div><!-- The container for the uploaded files --><div id="files" class="files"></div><br> - Insert the following javascript code
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100/*jslint unparam: true, regexp: true *//*global window, $ */$(function () {'use strict';// Change this to the location of your server-side upload handler:var url = 'server/',uploadButton = $('<button/>').addClass('btn btn-primary').prop('disabled', true).text('Processing...').on('click', function () {var $this = $(this),data = $this.data();$this.off('click').text('Abort').on('click', function () {$this.remove();data.abort();});data.submit().always(function () {$this.remove();});});$('#fileupload').fileupload({url: url,dataType: 'json',autoUpload: false,acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,maxFileSize: 999000,// Enable image resizing, except for Android and Opera,// which actually support image resizing, but fail to// send Blob objects via XHR requests:disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),previewMaxWidth: 100,previewMaxHeight: 100,previewCrop: true}).on('fileuploadadd', function (e, data) {data.context = $('<div/>').appendTo('#files');$.each(data.files, function (index, file) {var node = $('<p/>').append($('<span/>').text(file.name));if (!index) {node.append('<br>').append(uploadButton.clone(true).data(data));}node.appendTo(data.context);});}).on('fileuploadprocessalways', function (e, data) {var index = data.index,file = data.files[index],node = $(data.context.children()[index]);if (file.preview) {node.prepend('<br>').prepend(file.preview);}if (file.error) {node.append('<br>').append($('<span class="text-danger"/>').text(file.error));}if (index + 1 === data.files.length) {data.context.find('button').text('Upload').prop('disabled', !!data.files.error);}}).on('fileuploadprogressall', function (e, data) {var progress = parseInt(data.loaded / data.total * 100, 10);$('#progress .progress-bar').css('width',progress + '%');}).on('fileuploaddone', function (e, data) {$.each(data.result.files, function (index, file) {if (file.url) {var link = $('<a>').attr('target', '_blank').prop('href', file.url);$(data.context.children()[index]).wrap(link);} else if (file.error) {var error = $('<span class="text-danger"/>').text(file.error);$(data.context.children()[index]).append('<br>').append(error);}});}).on('fileuploadfail', function (e, data) {$.each(data.files, function (index) {var error = $('<span class="text-danger"/>').text('File upload failed.');$(data.context.children()[index]).append('<br>').append(error);});}).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');});
Explanation:
Change the URL variable to place the location of the uploaded image
Run the app in the browser using the URL as follows
“HTTP: //localhost/uploadimages/application/upload/upload3.php“.
The application will run like the following picture
From the above three examples, you can apply to your application system integrated with the adminLTE framework.
To download the example above please share this article using the button below to get the download link
[sociallocker id=58]
url :php tutorial how to upload image with three different method example project download
password : seegatesite.com
[/sociallocker]
Hi Have shared your page on tweeter using the tweeter button at the top but your download buttons are not showing
url : https://seegatesite.com/php-tutorial-how-to-upload-image-using-php-with-3-different-method-example-project/
password : seegatesite.com