php jquery image upload - php

i have a script that uploads an image into a folder instead of saving it as a blob..
<?php
mysql_connect('localhost','root','')or die(mysql_error());
mysql_select_db('db_tourism')or die(mysql_error());
//$newname='baro.jpg';
//dir:[../../]
$uploaddir = '../../images/municipality/';
$cc=$uploaddir.$fileName;
$fileName = $_FILES['uploadfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$ext = end(explode('.', $fileName));
$newname=$fileName;//.'.'.$ext;
$file = $uploaddir .$newname; //basename($_FILES['uploadfile']['name']);
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
// echo "<script>alert('success:$fileName');</script>";
mysql_query("INSERT INTO `_temp-image` ( `id` , `File_name` , `path` )
VALUES (
NULL , '$fileName', '$file'
);");
echo "success";
}
else {
echo "error";
}
?>
and here is the jquery
var btnUpload=$('#uploada');
//var btnUploadTxt=$('#uploada').attr('value');
var status=$('#status');
new AjaxUpload(btnUpload, {
action: 'upload-file.php',
name: 'uploadfile',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
// extension is not allowed
btnUpload.val('Only JPG, PNG or GIF files are allowed');
return false;
}
btnUpload.val('Uploading...');
},
onComplete: function(file, response){
//On completion clear the status
btnUpload.val('Upload Picture');
//Add uploaded file to list
if(response==="success"){
$('<li class="uplod" uid="_temp-image" title="click to remove ['+file+']" id="'+file+' "><span id=" '+file+' " style="font- family:calibri;font-size:10px;" >'+file+' [UPLOADED]</span></li>').appendTo('#uploaded');/ *.html('<img src="../uploaded_image/'+file+'" alt="" />'+file)*///.addClass('success');
} else{
$('<li></li>').appendTo('#uploaded').text(fi le).addClass('error');
}
}
});
it works fine i can add and delete picture... BUT my problem is handling DUPLICATE files... how to error trap if that kind of image is already uploaded??

Generate CRC checksum, MD5 or other hash type for image binary data and store that hash in database.
After upload - check new image checksum/hash and compare it with that stored in database.
Use md5_file function.
$md5hash = md5_file(string $filename);
Here is more: http://www.php.net/manual/en/function.md5-file.php

Related

Having problem with uploading multiple files in one request using dropzone

Am trying to update user image database column using dropzone plugin in one request but when i set uploadMultiple to true is not working no image move to folder neither database. But when i set it to false only last image name move to user image column but all images move to folder.
Thanks in advance
Here is my code
Dropzone.options.mydropzone =
{
autoProcessQueue: false,
addRemoveLinks: true,
dictMaxFilesExceeded: "Maximum upload limit reached",
dictInvalidFileType: "upload only JPG/PNG/JPEG/GIF/BMP",
acceptedFiles: '.png,.jpg,.jpeg,.gif,.bmp',
parallelUploads: 10,
// uploadMultiple: true,
init: function ()
{
var submitButton = document.querySelector('#letupload');
myDropzone = this;
submitButton.addEventListener("click", function(){
myDropzone.processQueue();
});
this.on("complete", function(){
if (this.getQueuedFiles().length == 0 && this.getUploadingFiles().length == 0)
{
var _this = this;
_this.removeAllFiles();
}
//console.log(this.getUploadingFiles());
});
},
};
Server Side
if (!empty($_FILES)) {
$temp_file = $_FILES['file']['tmp_name'];
$targetDir = '../../user_images/';
$filename = rand().$_FILES['file']['name'];
$targetFile = $targetDir.$filename;
if (move_uploaded_file($temp_file, $targetFile)) {
$sql="UPDATE img SET Image='$filename' WHERE User_id = '$memberid' ";//
if(!$qsql=mysqli_query($con,$sql))
{
echo mysqli_error($con);
}
}
}
After follow Mohammed link every images to to destination folder but only last image save into that database Below is my new server side code
if (!empty($_FILES)) {
foreach($_FILES['file']['tmp_name'] as $key => $value) {
$temp_file = $_FILES['file']['tmp_name'][$key];
$targetDir = '../../user_images/';
$filename = rand().$_FILES['file']['name'][$key];
$targetFile = $targetDir.$filename;
if (move_uploaded_file($temp_file,$targetFile)) {
$sql="UPDATE img SET Image='$filename' WHERE User_id = '$memberid' ";//
if(!$qsql=mysqli_query($con,$sql))
{
echo mysqli_error($con);
}
}
}
}
You are updating at each iteration , so the value at the end of script will be the name of the last image uploaded , so there is a way to solve this issue trying this snippet of code :
Insert into an array (i nammed id $images) the file name of uploaded
files.
convert array into spring separated by comma , using implode
function .(i used the same variable $images).
update the row with images name .
Code example :
if (!empty($_FILES)) {
$images=array[];
foreach($_FILES['file']['tmp_name'] as $key => $value) {
$temp_file = $_FILES['file']['tmp_name'][$key];
$targetDir = '../../user_images/';
$filename = rand().$_FILES['file']['name'][$key];
$targetFile = $targetDir.$filename;
if (move_uploaded_file($temp_file,$targetFile)) {
$images[]= $filename;
}
}
$images = implode(',',$images);
$sql="UPDATE img SET Image='$images' WHERE User_id = '$memberid' ";//
if(!$qsql=mysqli_query($con,$sql)){
echo mysqli_error($con);
}
}
Hope this help you .
Thanks to #Mohammed after I try your code, the problem of saving images name into database still persist, I now discover that you declare empty array inside the foreach so below is the working code
Dropzone Js
Dropzone.options.mydropzone =
{
autoProcessQueue: false,
addRemoveLinks: true,
dictMaxFilesExceeded: "Maximum upload limit reached",
dictInvalidFileType: "upload only JPG/PNG/JPEG/GIF/BMP",
acceptedFiles: '.png,.jpg,.jpeg,.gif,.bmp',
parallelUploads: 10,
uploadMultiple: true,
init: function ()
{
var submitButton = document.querySelector('#letupload');
myDropzone = this;
submitButton.addEventListener("click", function(){
myDropzone.processQueue();
});
this.on("complete", function(file, response){
if (this.getQueuedFiles().length == 0 && this.getUploadingFiles().length == 0)
{
var _this = this;
_this.removeAllFiles();
}
console.log(this.getUploadingFiles());
});
},
};
Server Side
if (!empty($_FILES)) {
$empty_img_arr=array();
foreach($_FILES['file']['tmp_name'] as $key => $value) {
$temp_file = $_FILES['file']['tmp_name'][$key];
$targetDir = '../../user_images/';
$filename = rand().$_FILES['file']['name'][$key];
$targetFile = $targetDir.$filename;
if (move_uploaded_file($temp_file,$targetFile)) {
$empty_img_arr[]= $filename;
$image = implode(',',$empty_img_arr);
$sql="UPDATE img SET Image='$image' WHERE User_id = '$memberid' ";//
if(!$qsql=mysqli_query($con,$sql))
{
echo mysqli_error($con);
}
}
}
}
Thanks so much really appreciate

Php sql 3way image upload form

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.');
}
}

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().

Upload image and preview on div without refresh - PHP / AJAX

I know how upload an image by a form in php. This is my php-code:
<?php
include('include/db.inc.php');
if(!isset($_SESSION))
{
session_start();
}
if(isset($_SESSION['username']))
{
$username = $_SESSION['username'];
$valid_exts = array('jpeg', 'jpg', 'png', 'gif');
$max_size = 200 * 1024;
$path = "../php/data/users/".$username."/";
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if(!empty($_FILES['image']))
{
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
if(in_array($ext, $valid_exts) && $_FILES['image']['size'] < $max_size)
{
$path = $path . 'profile.jpg';
if (move_uploaded_file($_FILES['image']['tmp_name'], $path))
{
$sql = 'UPDATE users SET img_src = "profile.jpg" WHERE username_crypt = "'.$username.'"';
$result = mysql_query($sql) or die("Query error: ".mysql_error());
echo("Success");
}
}
else
{
echo ("InvalidFile");
}
}
else
{
echo ("FileNotUploaded");
}
}
else
{
echo ("BadRequest");
}
}
?>
After the upload, I take the uploaded image by php and the upload works.
But my question is: I have a div in HTML page where there's already an image selected by php. I would upload the new image and replace this without refresh of the page. I would upload the image and after the upload I would see the new image change the previous. I don't know how I could do that. I don't know how I can use AJAX in this context. I would obviously control the errors that php makes during the upload.
I would only click on a button that chooses the image, upload that image and then change the image div with the new uploaded picture without any refresh.
Thank you :D
You could take a look at jQuery File Upload: http://blueimp.github.io/jQuery-File-Upload/
Indeed, you need to use AJAX.
You can use this code below:
<script>
$.ajax({
type: "POST",
url: "YOUR-PHP-URL",
data: YOUR-DATA,
success: function(data){
$('YOUR-DIV').HTML(HERE-YOUR-NEW-IMAGE);
},
error: function(data){
Do-SOMETHING-IF-YOU-WANT
}
})
</script>
Your PHP looks oke, after succes you need to echo the path of the image. The 'data' var in success would be the path that you echo'd you now only need to replace the old image using jQuery. I'm not sure if you can do that only with .HTML() but i think this would work.

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