Php sql 3way image upload form - php

Im currently prepairing a web page and i need to make a form to upload image. It must be possible user to,
1 upload image by url ,
2 upload image by computer ,
3 upload image by drag and dropping.
I found those code separately from the internet.
But problem is how to combine all of those.
Html Form has 2 input box.
1 image name.
2 image url, upload image button
When user upload image it must be save to folder as name in 1st input box.also it name need to save in sql with the extention.
Can any one help me!
--------------html------------------
<input name="file_name" placeholder="File Name" class="form-control" type="text">
--------------php----------------
if (isset($_POST['add'])){
$softname=$_POST['file_name'];
}
require_once('ImageManipulator.php');
if ($_FILES['fileToUpload']['error'] > 0) {
echo "Error: " . $_FILES['fileToUpload']['error'] . "<br />";
}
else {
$validExtensions = array('.jpg', '.jpeg', '.gif', '.png','.bmp');
$fileExtension = strrchr($_FILES['fileToUpload']['name'], ".");
// check if file Extension is on the list of allowed ones
if (in_array($fileExtension, $validExtensions)) {
$newNamePrefix = 'ddownload_';
$manipulator = new ImageManipulator($_FILES['fileToUpload']['tmp_name']);
$newImage = $manipulator->resample(250, 250);
if(isset($_POST['img_url'])){
$url=$_POST['img_url'];
if (!empty($url)) {
$data = file_get_contents($url);
$manipulator = new ImageManipulator( $data);
// resizing to 200x200 image from url
$newImage = $manipulator->resample(250, 250);
}
// saving file to uploads folder
$manipulator->save('uploads/img/' . $newNamePrefix . $softname);
echo 'Thank you! ...';
} else {
echo 'You must upload an image...';
}
}
$source=$_POST['directlink'];
$u_image=$softname;
$filesize=$_POST['size'];
$type=$_POST['type'];
$description =$_POST['description'];
$insert_data="INSERT INTO `softwarelist`(`sid`, `softname`, `image`, `type`, `source`,`description`,`rating`,`filesize`,`user`) VALUES ('','$softname','$u_image','$type','$source','$description','','$filesize','');";
-------------end php----------
------------script for drag AND drop image-------
<script>
var files = evt.target.files;
var files = evt.dataTransfer.files;
var result = '';
var file;
for (var i = 0; file = files[i]; i++) {
// if the file is not an image, continue
if (!file.type.match('image.*')) {
continue;
}
reader = new FileReader();
reader.onload = (function (tFile) {
return function (evt) {
var div = document.createElement('div');
div.innerHTML = '<img style="width: 200px;" src="' + evt.target.result + '" />';
document.getElementById('filesInfo').appendChild(div);
};
}(file));
reader.readAsDataURL(file);
}
} else {
alert('The File APIs are not fully supported in this browser.');
}
}

Related

Is this good way how to resize image before upload?

I cannot find some good solution fitted for me for resizing images before upload via PHP so I tried to make own one. But I do not know if there are some problems connected with my solution. I use imagexxx function instead of move_uploaded_file.
Can you please advice me if it is good way and also help to check if security of my code is enough for real use?
UPLOAD PHP code:
<?php
require($_SERVER['DOCUMENT_ROOT'] . '/bazar/_inc/DBController.php');
require($_SERVER['DOCUMENT_ROOT'] . '/bazar/_inc/functions.php');
include_once($_SERVER['DOCUMENT_ROOT'] . '/_inc/vendor/autoload.php');
// inicialize object
$db_handler = new DBController();
// get total number of files in file list
$total_files = count($_FILES['files']['name']);
// array(5) { ["name"]=> array(2) { [0]=> string(23) "IMG_20190916_105311.jpg" [1]=> string(19) "20180525_115635.jpg" } ["type"]=> array(2) { [0]=> string(10) "image/jpeg" [1]=> string(10) "image/jpeg" } ["tmp_name"]=> array(2) { [0]=> string(28) "/home/gm016900/tmp/phpdU58AU" [1]=> string(28) "/home/gm016900/tmp/phpIqWoaQ" } ["error"]=> array(2) { [0]=> int(0) [1]=> int(0) } ["size"]=> array(2) { [0]=> int(306091) [1]=> int(2315700) } }
// Create array for jQuery information
$return_arr = array();
$images_names = array_filter($_FILES['files']['name']); // filter just values for $key = name
// -> array(2) { [0]=> string(23) "IMG_20190916_105311.jpg" [1]=> string(19) "20180525_115635.jpg" }
//var_dump($images_names);
// set width and height for thumbnail
$thumb_width = 300;
$uploaded_img_width = 1024;
//$thumb_height = 270;
/* BATCH FILE UPLOAD */
// if $_FILES contains image then do foreach
if ( !empty($images_names) ) {
for($i = 0; $i < $total_files; $i++) {
// Get reference to uploaded image
$image_file = $_FILES["files"];
// Get image name
$image_name = $_FILES["files"]["name"][$i];
// Get file size
$image_size = $_FILES["files"]["size"][$i];
/* BASIC CONTROL */
// Exit if no file uploaded or image name contains unvalid characters /, \\
if ( ( !strpos($image_name, '/') || !strpos($image_name, '\\') ) && isset($image_file) ) {
// define variables if image in correct format is uploaded
$errors = array();
$maxsize = 10485760;
$acceptable = array(
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
} else {
$errors = 'No image uploaded.';
}
// Exit if image file is zero bytes or if image size is more then 10 MB
if (getimagesize($image_file["tmp_name"][$i]) <= 0) {
$errors = 'Uploaded file has no contents.';
} elseif ($image_size >= $maxsize) {
$errors = 'Image is too large. Image must be less than 10 megabytes.';
}
if($_FILES['userfile']['error']==UPLOAD_ERR_OK) {
$errors = $_FILES['userfile']['error'];
}
// Determine the type of an image int|false
$image_type = exif_imagetype($image_file["tmp_name"][$i]);
// Exit if is not a valid image file or image has not supported type
if (!$image_type) {
$errors = 'Uploaded file is not an image.';
} elseif ( !in_array($image_file["type"][$i], $acceptable) ) {
$errors = 'Image has not supported type JPG, JPEG, PNG, GIF.';
} else {
$src = "default.png";
}
if ($errors) { flash()->warning( 'Something went wrong' ); }
/* CREATE RANDOM IMAGE NAME INSTEDAOF $_FILES['files']['name'] */
// Get file extension based on file type, to prepend a dot we pass true as the second parameter
$image_extension = image_type_to_extension($image_type, true);
// Create a unique image name
$random_image_name = bin2hex(random_bytes(16)) . $image_extension;
/* DEFINE LOCATION */
// Create adress with new img random name
$relative_location = "/bazar/assets/img/photos/".$random_image_name;
$absolute_location = dirname(__DIR__, 2).$relative_location;
$thumb_relative_location = "/bazar/assets/img/photos/thumbs/".$random_image_name;
$thumb_absolute_location = dirname(__DIR__, 2).$thumb_relative_location;
//var_dump($image_file["tmp_name"][$i]);
var_dump($_FILES["files"]["tmp_name"]);
/* MOVE TEMP IMG TO PHOTOS FOLDER */
// Move img with tmp_name to new location under new random name added from define location section
//if (move_uploaded_file($image_file["tmp_name"][$i], $absolute_location)) { // move tmp_file to relative_location
resizeandUpload($random_image_name, $uploaded_img_width, $_FILES["files"]["tmp_name"][$i], $absolute_location);
/* INSERT IMG_PATH AND THUMB_PATH TO DB */
$item_id = 1; // get from previous query
$src = $relative_location;
//$thumb_src = $thumb_relative_location;
$query = "INSERT INTO photos (item_id, img_path, thumb_path) VALUES (?, ?, ?)";
$inserted = $db_handler->runQuery( $query, 'iss', array($item_id, $src, $thumb_src) );
//$return_arr .= array("name" => $random_image_name,"size" => $image_size, "src"=> $src);
/* CREATE THUMBNAIL */
createThumbnail($random_image_name, $thumb_width, $absolute_location, $thumb_absolute_location);
//}
}
}
//echo json_encode($return_arr);
FUNCTIONS PHP code:
<?php
/**
* Secure Output from DB
*
* Secure output from db against XSS attacks
*
* #param string $str
* #return string
*/
function plain ($str) {
// protection against unauthorized access to code
return htmlspecialchars( $str, ENT_QUOTES);
}
/**
* Long Text to Short Text
*
* Short Long Text to Setted up Lenght
*
* #param string $text, int $lenght
* #return string
*/
function shortText ($text, $lenght = 180) {
if ( strlen($text) > $lenght ) {
$result = substr($text, 0, $lenght) . 'Viac...';
return $result;
} else {
return $text;
}
}
function createThumbnail($filename, $thumb_width, $upload_image_path, $upload_thumbs_path) {
$upload_image = $upload_image_path;
$thumbnail_image = $upload_thumbs_path;
list($width,$height) = getimagesize($upload_image);
$thumb_height = floor($height * ($thumb_width / $width)); // decrease height same percentage as width
$thumb = imagecreatetruecolor($thumb_width,$thumb_height); // imagecreatetruecolor() returns an image object representing a black image of the specified size.
// imagecreatefromjpeg function, which creates the image resource in memory out of the source image path which was initialized in the constructor
if(preg_match('/[.](jpg|jpeg)$/i', $filename)) {
$image_source = imagecreatefromjpeg($upload_image);
} else if (preg_match('/[.](gif)$/i', $filename)) {
$image_source = imagecreatefromgif($upload_image);
} else if (preg_match('/[.](png)$/i', $filename)) {
$image_source = imagecreatefrompng($upload_image);
} else {
$image_source = imagecreatefromjpeg($upload_image);
}
// Copy and resize part of the image with resampling based on the provided parameters and generates the thumbnail image in memory.
imagecopyresampled($thumb,$image_source,0,0,0,0,$thumb_width,$thumb_height,$width,$height);
// imagejpeg function which saves the in-memory thumbnail image to the desired path on the disk
if(preg_match('/[.](jpg|jpeg)$/i', $filename)) {
imagejpeg($thumb,$thumbnail_image,100);
} else if (preg_match('/[.](gif)$/i', $filename)) {
imagegif($thumb,$thumbnail_image,100);
} else if (preg_match('/[.](png)$/i', $filename)) {
imagepng($thumb,$thumbnail_image,100);
} else {
imagejpeg($thumb,$thumbnail_image,100);
}
}
function resizeAndUpload($filename, $thumb_width, $upload_temp_image_path, $upload_image_path) {
$upload_image = $upload_temp_image_path;
$thumbnail_image = $upload_image_path;
list($width,$height) = getimagesize($upload_image);
$thumb_height = floor($height * ($thumb_width / $width)); // decrease height same percentage as width
$thumb = imagecreatetruecolor($thumb_width,$thumb_height); // imagecreatetruecolor() returns an image object representing a black image of the specified size.
var_dump($upload_image);
var_dump($thumb);
// imagecreatefromjpeg function, which creates the image resource in memory out of the source image path which was initialized in the constructor
if(preg_match('/[.](jpg|jpeg)$/i', $filename)) {
$image_source = imagecreatefromjpeg($upload_image);
} else if (preg_match('/[.](gif)$/i', $filename)) {
$image_source = imagecreatefromgif($upload_image);
} else if (preg_match('/[.](png)$/i', $filename)) {
$image_source = imagecreatefrompng($upload_image);
} else {
$image_source = imagecreatefromjpeg($upload_image);
}
var_dump($image_source);
// Copy and resize part of the image with resampling based on the provided parameters and generates the thumbnail image in memory.
imagecopyresampled($thumb,$image_source,0,0,0,0,$thumb_width,$thumb_height,$width,$height);
// imagejpeg function which saves the in-memory thumbnail image to the desired path on the disk
if(preg_match('/[.](jpg|jpeg)$/i', $filename)) {
imagejpeg($thumb,$thumbnail_image,100);
} else if (preg_match('/[.](gif)$/i', $filename)) {
imagegif($thumb,$thumbnail_image,100);
} else if (preg_match('/[.](png)$/i', $filename)) {
imagepng($thumb,$thumbnail_image,100);
} else {
imagejpeg($thumb,$thumbnail_image,100);
}
}
JS code:
(function($) {
/* SIDE SCROLL WHOLE */
var scrollArea = $('.left-arrow').next(),
scrollEnd = scrollArea.width(),
leftArrow = $('.left-arrow'),
rightArrow = $('.right-arrow');
leftArrow.hide();
rightArrow.click(function () {
event.preventDefault();
$(this).prev().animate({scrollLeft: scrollEnd}, 1000); // scroll just area belong to the arrow
leftArrow.show();
rightArrow.hide();
});
leftArrow.click(function () {
event.preventDefault();
$(this).next().animate({scrollLeft: 0}, 1000); // scroll just area belong to the arrow
leftArrow.hide();
rightArrow.show();
});
/* SIDE SCROLL PARTIAL*/
/*
var leftArrowPartial = $('.left-arrow-partial'),
rightArrowPartial = $('.right-arrow-partial'),
scrollAreaPartial = leftArrowPartial.next(),
frameWidth = scrollAreaPartial.width(), // width of div showed on display
scrollElmtWidth = scrollAreaPartial[0].scrollWidth, // width of div also with hidden part
scrollAmount = 0,
distance = 0,
maxDistance = scrollElmtWidth - frameWidth, // width of whole also with hidden part - width which must be uncovered by scrolling
scrollStep = maxDistance/3; // divide all resolution to 4 steps
leftArrowPartial.hide(); // if it is start of scrolling area, no need left arrow
rightArrowPartial.click(function () {
event.preventDefault();
distance = scrollAreaPartial.scrollLeft();
// if scrolled distance is less then max distance + 1/4 px each time -> after max distance have not to count + 1/4 px
if (distance < maxDistance) {
scrollAmount += scrollStep;
// scroll just area belong to the arrow
$(this).prev().animate({scrollLeft: scrollAmount}, 100);
leftArrowPartial.show();
}
// hide right arrow on end of srolling area
if (scrollAmount >= maxDistance) {
rightArrowPartial.hide();
}
});
leftArrowPartial.click(function () {
event.preventDefault();
distance = scrollAreaPartial.scrollLeft();
//if (scrollAmount > maxDistance) {scrollAmount = maxDistance}
// if it is start of scroll area -> cannot discount - 1/4 px
if (scrollAmount > 0) {
scrollAmount -= scrollStep;
// scroll just area belong to the arrow
$(this).next().animate({scrollLeft: scrollAmount}, 100);
rightArrowPartial.show();
}
// hide right arrow on start of srolling are
if (scrollAmount <= 0) {
leftArrowPartial.hide();
}
});*/
/* DRAG AND DROP IMG UPLOAD */
// preventing page from redirecting
$("html").on("dragover", function(e) {
e.preventDefault();
e.stopPropagation();
});
$("html").on("drop", function(e) { e.preventDefault(); e.stopPropagation(); });
// Drag enter
$('.add-item__upload-area').on('dragenter', function (e) {
e.stopPropagation();
e.preventDefault();
});
// Drag over
$('.add-item__upload-area').on('dragover', function (e) {
e.stopPropagation();
e.preventDefault();
$('.add-item__dropzone').css({border: '2px dashed #111'});
});
$('.add-item__upload-area').on('dragleave', function (e) {
e.stopPropagation();
e.preventDefault();
$('.add-item__dropzone').css({border: '2px dashed #888'});
});
// Open file browser
$('.add-item__add-photo-btn').click(function() {
$('#input-files').trigger('click'); // execute input type file after click on button
event.preventDefault();
});
// create object to keep img files for modification
var data = {};
// Files added by drop to dropzone area
$('.add-item__upload-area').on('drop', function (e) {
e.stopPropagation();
e.preventDefault();
var totalFiles = e.originalEvent.dataTransfer.files.length;
// fill form by files from input
for (var i = 0; i < totalFiles; i++) {
var file = e.originalEvent.dataTransfer.files[i], // Get list of the files dropped to area
url = URL.createObjectURL(file);
// Control of size and format
if (file) {
var fileType = file.type, // get image format (jpg, gif, ...)
fileSize = file.size, // get file size
maxFileSize = 10485760, // set up max file size
typeReg = /^image\/(jpg|png|jpeg|gif)$/; // allow jpg, png, jpeg, gif
if ( typeReg.test(fileType) && fileSize <= maxFileSize ) {
// fill object for file modifications by img files
data['file_'+i] = file;
// create temp url to img object for creating thumbnail and append img with temp src to thumbnail__wraper div
$('.thumbnail__wrapper').append('<div class="thumbnail" id="file_'+ i +'"><img class="imageThumb" src="' + url + '" title="' + file.name + '"/><br/><a class="remove">Zmazať</a></div>');
$('.add-item__add-photo-btn-area').find('p').hide();
//URL.revokeObjectURL(url);
} else {
if (!typeReg.test(fileType)) {
alert('This file type is unsupported.');
} else if (fileSize > maxFileSize) {
alert('This file reach max supported size.');
}
}
}
}
});
// Files added by selecting in file browser
$('#input-files').on('change', function(){
var totalFiles = $('#input-files')[0].files.length; // get number of uploaded files from input element
// modify ordering of fields inside data object according to order from sortable ui
for (var i = 0; i < totalFiles; i++) {
// By appending [0] to the jQuery object will return the first DOM element. Get <input> element from object.
var file = $('#input-files')[0].files[i], // Get first file from list of files selected with the <input type="file">
url = URL.createObjectURL(file);
if (file) {
var fileType = file.type, // get image format (jpg, gif, ...)
fileSize = file.size, // get file size
maxFileSize = 10485760, // set up max file size
typeReg = /^image\/(jpg|png|jpeg|gif)$/; // allow jpg, png, jpeg, gif
if ( typeReg.test(fileType) && fileSize <= maxFileSize ) {
// fill object for file modifications by img files
data['file_'+i] = file;
// create temp url to img object for creating thumbnail and append img with temp src to thumbnail__wraper div
$('.thumbnail__wrapper').append('<div class="thumbnail" id="file_'+ i +'"><img class="imageThumb" src="' + url + '" title="' + file.name + '"/><br/><a class="remove">Zmazať</a></div>');
$('.add-item__add-photo-btn-area').find('p').hide();
//URL.revokeObjectURL(url);
} else {
if (!typeReg.test(fileType)) {
alert('This file type is unsupported.');
} else if (fileSize > maxFileSize) {
alert('This file reach max supported size.');
}
}
}
}
//console.log(data);
//uploadData(formData); // send data via ajax to upload.php
});
// Remove field of data obj after click on remove button
$('.add-item__dropzone').on('click','.remove', function() {
// remove choosen field
delete data[$(this).parent().attr('id')];
$(this).parent('.thumbnail').remove();
if ($(this).parent('.thumbnail').empty()) {
$('.add-item__add-photo-btn-area').find('p').show();
}
});
// Make images sortable
$('.thumbnail__wrapper').sortable({
axis: 'x', // axis in which sort is possible
update: function (event, ui) {
// get all ids (item-1, ....) from li elements (setted as sortable) of list in form item[]=1&item[]=2
var reorderList = $(this).sortable('serialize');
//console.log(reorderList);
// fill FormData object by files from data array after order change
var formData = new FormData();
var dataLength = Object.keys(data).length;
//console.log(data);
data = changeOrder(data, reorderList);
//console.log(data);
}
});
// Change order of files inside object data
function changeOrder(obj, order) {
var newObject = {};
// if the g flag is used, all results matching the complete regular expression will be returned, but capturing groups will not.
var matches = order.match(/=/g);
var count = matches.length;
// file[]=1&file[]=0&file[]=2 => ["file[]=1", "file[]=0", "file[]=2"]
var arrayOfOrderValues = order.split('&');
// console.log(arrayOfOrderValues);
for (var i = 0; i < count; i++) {
// get values in appropriate format ["file[]=1", "file[]=0", "file[]=2"] => file_1, file_0, file_2
orderKey = 'file_' + arrayOfOrderValues[i].substring(arrayOfOrderValues[i].lastIndexOf("=") + 1);
// console.log(orderKeyValue);
// check if object contains key(property) as orderKeyValue and then do next step
if(obj.hasOwnProperty(orderKey)) {
// fill value of obj['file_1'] to newObject['file_0'] - ex. in first loop
newObject['file_'+i] = obj[orderKey];
}
}
return newObject;
};
// Sending AJAX request and upload file
function uploadData(formdata){
$.ajax({
url: '_inc/upload.php',
type: 'post',
data: formdata,
contentType: false,
processData: false,
dataType: 'json',
success: function(response){
//addThumbnail(response); // if success - create thumbnail
}
})
};
$('.test').on('submit', function() {
event.preventDefault();
//URL.revokeObjectURL();
var formData = new FormData(); // Create form
console.log(data);
var count = Object.keys(data).length; // count fields of object
for (var i = 0; i < count; i++) {
formData.append('files[]', data['file_'+i]); // append data to form -> (key, value), file[0] first file from list of files !!! key must have [] for array
}
console.log(count);
uploadData(formData); // send data via ajax to upload.php
});
})(jQuery);
Resizing an image before uploading it; I would do that on the client-side, and you can perfectly do that by using vanilla javascript only. Think about tons of users uploading the files to your server; that would mean tons of unnecessary server load. If you can do something on the client-side and that does not impact security, I'd do it on the client side.
To do it in js, proceed via the following steps:
Assume you have uploaded one file to:
<input type="file" id="my-upload" />
Grab the upload via:
const upload = document.getElementById('my-upload').files[0]
Eventually check the files' MIME type and its size to respect your conditions, via upload.type and upload.size.
Initiate a two-dimensional Canvas, which will be needed as frame to resize your image:
let canvas = document.createElement("canvas");
let canvasContext = canvas.getContext("2d");
Use the FileReader API to read your file into a base64 string:
let reader = new FileReader();
// Read the contents of the file
reader.readAsDataURL(upload);
Once that conversion finished, the load event will be triggered on your FileReader object, holding the according base64 string under the result property. This is where the real fun starts:
reader.onload = function () {
// Initiate image element; needed to retrieve the originally uploaded file's
// width and height, to maintain proportions while resizing
let dummyImg = new Image(
0,
0
);
// Set the 'src' attribute of that element to your string
dummyImg.src = this.result;
// The line above causes your base64 string to be loaded into the 'img'
// element. When that process finishes, the 'load' event is triggered on
// your image
dummyImg.onload = function () {
// Get the original width and height of the uploaded file
const origWidth = dummyImg.naturalWidth;
const origHeight = dummyImg.naturalHeight;
// Calculate ratio factor to maintain aspect ratio after resizing
// You may replace '300' with your desired width in pixels
const desiredWidth = 300;
const ratio = desiredWidth / origWidth;
// Calculate the corresponding height, matching 'desiredWidth'
const correspondingHeight = ratio * origHeight;
// Set canvas' width and height according to what has been calculated
canvas.width = desiredWidth;
canvas.height = correspondingHeight;
// Draw the image into the canvas
canvasContext.drawImage(
dummyImg,
0,
0,
desiredWidth,
correspondingHeight
);
// Convert resized image back to base64 string
const resizedImage = canvas.toDataURL(
upload.type,
1.0 // quality. change this to a value < 1.0 for mime types that allow
// lossy compression, such as jpeg, to allow for further compression
// (with quality loss though). On file types that do not allow for
// lossy compression, this value will have no effect.
);
// 'resizedImage' will be the base64 string representation of your
// uploaded file, resized based on a width of 300 pixels,
// conserving the aspect ratio. You can now simply submit that to your
// server, as PHP works pretty well with base64 strings when it comes to
// file contents.
// Note that you do not need formData for this anymore, now that
// you're working with a simple (base64) string; you can easily
// submit the data as simple string to the server. So try to
// simply submit the value 'resizedImage' to your server HERE,
// just like you would submit any other string, and grab it on
// your server side like you would do it with any other string
// If you bind this code as change listener to your upload element
// , I would store the value of 'resizedImage' in a variable,
// which you then submit to the server upon form submit. I
// leave that decision up to you.
}
}
CONCRETE IMPLEMENTATION
// Initiate storage variable for resized image
var resizedFile;
function resizeImage() {
const upload = document.getElementById('your-upload').files[0];
let canvas = document.createElement("canvas");
let canvasContext = canvas.getContext("2d");
let reader = new FileReader();
reader.readAsDataURL(upload);
reader.onload = function () {
let dummyImg = new Image(
0,
0
);
dummyImg.src = this.result;
dummyImg.onload = function () {
const origWidth = dummyImg.naturalWidth;
const origHeight = dummyImg.naturalHeight;
const desiredWidth = 300;
const ratio = desiredWidth / origWidth;
const correspondingHeight = ratio * origHeight;
canvas.width = desiredWidth;
canvas.height = correspondingHeight;
canvasContext.drawImage(
dummyImg,
0,
0,
desiredWidth,
correspondingHeight
);
const resizedImage = canvas.toDataURL(
upload.type,
1.0
);
// If you bind this code as change listener to your upload element
// , I would store the value of 'resizedImage' in a variable,
// which you then submit to the server upon form submit. I
// leave that decision up to you. Personally, I prefer storing
// the obtained base64 string in a variable, and then post to
// the server on submit.
resizedFile = resizedImage;
}
}
}
// Attach as change listener to your <input type="file" id="your-upload"/> element, such that it reacts everytime you upload a file
document.getElementById('your-upload').addEventListener('change',resizeImage);
So finally (after little wake up - I realized that onload is asynchronous function) I implemented code from DevelJoe in this way. I do not know if it is correct way but I hope I did not screw it up.
During each change event on input field type file
I check size and img type and then resize image and then create preview
// Files added by selecting in file browser
$('#input-files').on('change', function(){
var totalFiles = $('#input-files')[0].files.length; // get number of uploaded files from input element
// Fill form by files from input
for (var i = 0; i < totalFiles; i++) {
// By appending [0] to the jQuery object will return the first DOM element. Get <input> element from object.
var file = $('#input-files')[0].files[i]; // Get first file from list of files selected with the <input type="file">
// If file is not empty control size and type and show temp image
if (file) {
if ( checkImageTypeAndSize(file) ) {
resizeImageAndCreatePreview(file);
}
}
}
});
Here is my modified code for image resizing:
I added function to convert base64 img to blob
then I create new File and storage files in object data which I can modify due to sortable function
after submit I upload all files to server via upload.php
/* IMAGE RESIZE */
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
function resizeImageAndCreatePreview(file) {
const upload = file;
var resizedFile;
let canvas = document.createElement("canvas");
let canvasContext = canvas.getContext("2d");
let reader = new FileReader();
reader.readAsDataURL(upload);
reader.onload = function () {
let dummyImg = new Image(
0,
0
);
dummyImg.src = this.result;
dummyImg.onload = function () {
const origWidth = dummyImg.naturalWidth;
const origHeight = dummyImg.naturalHeight;
const desiredWidth = 1024;
const ratio = desiredWidth / origWidth;
const correspondingHeight = ratio * origHeight;
canvas.width = desiredWidth;
canvas.height = correspondingHeight;
canvasContext.drawImage(
dummyImg,
0,
0,
desiredWidth,
correspondingHeight
);
const resizedImage = canvas.toDataURL(
upload.type,
1.0
);
var resizedFileURL = resizedImage;
var blob = dataURItoBlob(resizedFileURL);
resizedFile = new File( [blob], upload.name, { type: upload.type, size: upload.size } );
var url = URL.createObjectURL(resizedFile);
mark = Math.random().toString(36).slice(2, 7);
// fill object for file modifications by img files
data['file_'+mark] = resizedFile;
// create temp url to img object for creating thumbnail and append img with temp src to thumbnail__wraper div
$('.thumbnail__wrapper').append('<div class="thumbnail" id="file_'+ mark +'"><img class="imageThumb" src="' + url + '" title="' + file.name + '"/><br/><a class="remove">Zmazať</a></div>');
$('.add-item__add-photo-btn-area').find('p').hide();
console.log(data);
}
}
};
Please correct me if I do something wrong. This is first time I do something similar to this.

PHP MySQL jQuery Uploading Multiple Files to server issue

I just finished designing a basic site to upload some files to the server, and store the file names in a database for searching functions. I designed the site using the following tutorial: www.formget.com.
My problem is when I go to upload more than one file at a time, it appends the filenames together for a single file.
Example:
Filename Example
Here is my code for uploading the files:
$error = '';
if(isset($_POST['submit']))
{
$j = 0; // Variable for indexing uploaded image.
$target_path = 'uploads/'; // Declare path for uploaded images.
for($i = 0; $i < count($_FILES['file']['name']);$i++) // Loop to get individual element from the array.
{
$valid_ext = array('jpeg','jpg','png','gif'); // Extensions which are allowed.
$ext = explode('.', basename($_FILES['file']['name'][$i])); // Explode file name from dot(.)
$file_ext = end($ext); // Store extensions in the variable.
$filename = md5(uniqid());
$target_path = $target_path . $filename . '.' . $ext[count($ext) - 1]; // Set the target path with a new name of image.
if(($_FILES['file']['size'][$i] < 5000000) // Approx. 5MB files can be uploaded.
&& in_array($file_ext,$valid_ext))
{
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path))
{
// If file moved to uploads folder.
$success .= '<p class="success">('.$j.') Image uploaded successfully.</p>';
$date = date('Y-m-d H:i:s');
$stmt = $db->prepare('INSERT INTO uploads (filename,postdate,userid) VALUES (?,?,?)');
if($stmt)
{
$image = $filename . '.' . $ext[count($ext) - 1];
$stmt->bind_param('sss',$image,$date,$_SESSION['id']);
if($stmt->execute())
{
$success .= '<p class="success">('.$j.') Image added to database successfully.</p>';
}
else
{
$error .= '<p class="error">Error 34. Please contact the Site Administrator.</p>';
}
}
else
{
$error .= '<p class="error">Error 30. Please contact the Site Administrator.</p>';
}
}
else
{
$error .= '<p class="error">('.$j.') Please Try Again!</p>';
}
}
else
{
$error .= '<p class="error">('.$j.') Invalid file size or type.</p>';
}
$j = $j + 1; // Increment the number of uploaded images according to the files in the array.
}
}
Here is the jQuery:
var abc = 0; // Declare and define global increment value.
$(document).ready(function()
{
// To add new input file field dynamically, on click of "Add More Files" button, below function will be executed.
$('#add_more').click(function()
{
$(this).before($("<div/>",
{
id: 'filediv'
}).fadeIn('slow').append($("<input/>",
{
name: 'file[]',
type: 'file',
id: 'file'
}), $("<br/><br/>")));
});
// Following function will execute on change event of file input to select different file.
$('body').on('change', '#file', function()
{
if(this.files && this.files[0])
{
abc += 1; // Increment global variable by 1.
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd" + abc + "' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("abcd" + abc).append($("<img/>",
{
id: 'img',
src: 'x.png',
alt: 'delete'
}).click(function()
{
$(this).parent().parent().remove();
}));
}
});
// To Preview Image
function imageIsLoaded(e)
{
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e)
{
var name = $(":file").val();
if(!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
Any input as to why it keeps appending the filenames together would be appreciated. Please note that in the database, the filenames are correct, just not on the server itself in the uploads directory.
You are not resetting $target_path inside your for loop and therefore string concatenating it while looping. Results will be like A, AB, ABC, ... This is the issue:
$target_path = $target_path . $filename . '.' . $ext[count($ext) - 1];
You could create two variables.
$target_path = 'uploads/';
outside of your for-loop and use something like
$move_to_target = $target_path . $filename . '.' . $ext[count($ext) - 1];
inside your for-loop and update your call of move_uploaded_file to pass $move_to_target instead of $target_path. Your database entries are not affected because you build up the filename again in $image - this however seems bad practice (redundant code), if you want to enhance your code define $image first and then create $move_to_target like this:
$move_to_target = $target_path . $image;

Unable to upload file via custom WordPress plugin

I am developing custom WordPress plugin. In this plugin, I am trying to upload files into wp-content\uploads\passports (folder path).
I don't face any error message when uploading file. Although it shows File has been uploaded successfully. message, but there is no any uploaded file in the folder.
Here is my code:
trip-form.php
<tr><td cospan="4">Please attach a scanned copy of your:</td></tr>
<tr>
<td>Passport: </td>
<td colspan="3"><input type="file" name="passport" id="passport"/></td>
</tr>
<tr>
<td></td>
<td colspan="3"><div id="dropBox">
<p>Select file to upload</p>
</div></td>
</tr>
script.js
// Add events
$j('input[type=file]').on('change', fileUpload);
// File uploader function
function fileUpload(event){
alert('fileUpload');
//notify user about the file upload status
$j("#dropBox").html(event.target.value+" uploading...");
//get selected file
files = event.target.files;
//form data check the above bullet for what it is
var data = new FormData();
var web_url = document.location + '';
var path = web_url.substring(0,web_url.lastIndexOf('/'));
path = path.substring(0,path.lastIndexOf('/'));
path = path + '/wp-content/plugins/trip-form/pages/uploadfile.php';
//file data is presented as an array
for (var i = 0; i < files.length; i++) {
var file = files[i];
var fileExtension = ['jpeg', 'jpg', 'pdf'];
if ($j.inArray($j('#passport').val().split('.').pop().toLowerCase(), fileExtension) == -1) {
$j("#dropBox").html("Only formats are allowed : "+fileExtension.join(', '));
}else{
//append the uploadable file to FormData object
data.append('file', file, file.name);
//create a new XMLHttpRequest
var xhr = new XMLHttpRequest();
//post file data for upload
xhr.open('POST', path, true);
xhr.send(data);
xhr.onload = function () {
//get response and show the uploading status
var response = JSON.parse(xhr.responseText);
if(xhr.status === 200 && response.status == 'ok'){
$j("#dropBox").html("File has been uploaded successfully.");
}else{
$j("#dropBox").html("Some problem occured, please try again.");
}
};
}
}
}
uploadfile.php
<?php
$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );
//generate unique file name
$fileName = time().'_'.basename($_FILES["file"]["name"]);
//file upload path, targetdir is correct
$targetDir = "../../../uploads/passports/";
$targetFilePath = $targetDir . $fileName;
//upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
//if (file_exists ( $targetDir."testing.txt" )){
$response['status'] = 'ok';
}else{
$response['status'] = 'err';
}
//render response data in JSON format
echo json_encode($response);
?>
I have no idea what is wrong. Any help would be appreciated.
Thanks.
Can you please change your uploads folder permission. Make it 755.

Multiple Image upload and save path to database

I am working on a script that uploads multiple images and saves the path to database to fetch the images in each record separately. The images are uploaded well but the image name in the database are stored in the following format uploads/image_name.png which should be actually just image_name.png. Moreover when I upload multiple images a separate record is created in the database for each image. I want to display them in the same field. Here is the code I am using to upload the file to the database using php.
<?php
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$img = implode('',$_FILES['file']['name']);
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];
$title = (!empty($_POST['ad_title']))?$_POST['ad_title']:null;
$cat = (!empty($_POST['ad_cat']))?$_POST['ad_cat']:null;
$des = (!empty($_POST['ad_des']))?$_POST['ad_des']:null;
$name = (!empty($_POST['ad_name']))?$_POST['ad_name']:null;
$email = (!empty($_POST['ad_email']))?$_POST['ad_email']:null;
$phone = (!empty($_POST['ad_phone']))?$_POST['ad_phone']:null;
$state = (!empty($_POST['ad_state']))?$_POST['ad_state']:null;
//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 1024000) //Approx. 1mb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
$sql = "INSERT INTO ad_posting(img_name, ad_title, ad_cat, ad_des, ad_name, ad_email, ad_phone, ad_state)VALUES('$target_path', '$title','$cat','$des','$name','$email','$phone','$state')";
$frc = mysql_query($sql);
if ($frc){
echo "Success";
}else{
echo "Not Successful";
}
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else {//if file was not moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
This is the javascript code i m using.
var abc = 0; //Declaring and defining global increement variable
$(document).ready(function() {
//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
$('#add_more').click(function() {
$(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
$("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
$("<br/><br/>")
));
});
//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
if (this.files && this.files[0]) {
abc += 1; //increementing global variable by 1
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd"+ abc).append($("<img/>", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {
$(this).parent().parent().remove();
}));
}
});
//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
What is the error I am making? Please help me out solve the query.
from uploads/image_name.png to image_name.png.
$filename = 'uploads/image_name.png';
basename($filename);
in your sql
$sql = "INSERT INTO ad_posting(img_name, ad_title, ad_cat, ad_des, ad_name, ad_email, ad_phone, ad_state)VALUES('$target_path', '$title','$cat','$des','$name','$email','$phone','$state')";
if $target_path have the vale uploads/image_name.png then
$target_path = basename($target_path);
if you want the name of all images in the same field you can use implode().

Form not sending files other than images

I'm trying to upload files using php and I am copying and renaming files from other instances that are actually working (uploading pics). But for some reason the form is not passing (POST) any file that is NOT an image :-/
So, in resume, I am getting this (Google) 'request payload' for an image file:
------WebKitFormBoundaryrHOYostaC2KnUDlD
Content-Disposition: form-data; name="uploaded_file[]"; filename="image.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryrHOYostaC2KnUDlD--
But this for txt or pdf files:
------WebKitFormBoundaryc1RJOtSOpYKAZiBz--
Here is the form and script (functions are to avoid the user to click 'Submit', those work good):
echo '
<script language="JavaScript" type="text/javascript">
function HandleBrowseClick()
{
var fileinput = document.getElementById("uploaded_file");
fileinput.click();
}
function Handlechange()
{
var fileinput = document.getElementById("uploaded_file");
var textinput = document.getElementById("filename");
textinput.value = fileinput.value;
}
</script>';
echo '
<form enctype="multipart/form-data" target="_blank" name="send_file" id="send_file" method="post" action="file_upload.php">
<input type="file" class="hide button" id="uploaded_file" name="uploaded_file" onChange="Handlechange();"/>
<button type="submit" id="btn">Upload!</button>
</form>';
echo '
<div onclick="HandleBrowseClick();" id="fakeBrowse" >Load a file</div>
<input type="text" id="filename" size="50" readonly="true" />
';
So, since it's not passing anything, in my file_upload.php I get the "ERROR: Please browse for a file before clicking the upload button." or "Invalid argument supplied for foreach()" (if I expect an array) error.
I tried using application/x-www-form-urlencoded allowing the same result. Now for those who get mad if there is no question marks: Why the form works fine with images but not so with other kind of files? What am I dong wrong?
Here is the first few lines of file_upload.php (I don't think it's necessary but you never know):
$target = "../files/temp/";
foreach ($_FILES["uploaded_file"]["error"] as $key => $error) {
if ($error != UPLOAD_ERR_OK) { echo "error"; die;}
$fileName = $target . $_FILES["uploaded_file"]["name"][$key]; // The file name
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"][$key]; // File in the PHP tmp folder
$fileType = $_FILES["uploaded_file"]["type"][$key]; // The type of file it is
$fileSize = $_FILES["uploaded_file"]["size"][$key]; // File size in bytes
$fileErrorMsg = $_FILES["uploaded_file"]["error"][$key]; // 0 for false... and 1 for true last $key!!!
$fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); // filter the $filename
$fileName = strtolower($fileName);
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occurred while processing the file. Try again.";
exit();
}
Finally, some more js:
if (window.FormData) {
formdata = new FormData();
document.getElementById("btn").style.display = "none";
}
input.addEventListener("change", function (evt) {
document.getElementById("response").innerHTML = "Loading . . ."
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if (formdata) {
formdata.append("uploaded_file[]", file);
}
}
}
if (formdata) {
$.ajax({
url: "file_upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false
}).done(function (res) {
document.getElementById("response").innerHTML = res;
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
});
}
}, false);
where changing contentType doesn't make any diference
THANKS!!!
You have to define the MIME types for your files. For example
.pdf application/pdf
.doc application/msword
Okay, my bad. The js file has an image filter. It started working right away after I removed it.

Categories