Saving images into database - php

I'm trying to save images in a mysql database. It saves binary code into the table, but its corrupt and i can't display it. Also the size of the database field is bigger than the original file. Is there anything wrong in my code or in the approach im having.
I know thats its not a good practice to store images in a database, but im not in the position to decide it.
<div class="box-body">
<h3>Bilder</h3>
<form id="image_form">
<input type="file" name="frame" id="file_name" />
<input type="submit" value="Save">
</form>
</div>
$('#image_form').on("submit",(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: './index.php?action=585',
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
beforeSend: function (a) {
//a.overrideMimeType('image/jpeg; charset=UTF-8');
},
success: function (data) {
console.log(data);
},
error: function () {
location.reload();
}
});
}));
Back-End
//Get the content of the image and then add slashes to it
$tmpName = $_FILES['frame']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
var_dump($data);
$imagetmp = $data;
AccountDAO::updateResImages($imagetmp, $imagetmp, $imagetmp, $_SESSION['customer']->id);
Database
public static function updateResImages($img1, $img2, $img3, $customerid){
$db = new MySQLDatabase();
$sql = "UPDATE customer SET online_res_bild1 = ?, online_res_bild2 = ?, online_res_bild3 = ? WHERE customer_id = ? ";
$rs = $db->executeQuery($sql, 'sssi', $img1, $img2, $img3, $customerid);
$db->close();
return 1;
}

Related

how to send image data and other param from registration form to php

this is my ajax code
var fd = new FormData();
fd.append( 'file', $('#img')[0].files[0]);
var data = '&com='+company+'&loc='+location+'&year='+year+'&desc='+des+'&userid='+userid+'&fd='+fd;
$.ajax({
type : "POST",
url: "insert.php",
data : data,
success: function (response){
}
});
this is php code
$conn =new mysqli("localhost", "root", "","test2");
$company=isset($_POST['com']) ? $_POST['com']: '';
$local=isset($_POST['loc']) ? $_POST['loc']: '';
$year=isset($_POST['year']) ? $_POST['year']: '';
$description=isset($_POST['desc']) ? $_POST['desc']: '';
$userid=isset($_POST['userid']) ? $_POST['userid']: '';
$query = mysqli_query($conn,"call exp('$userid', '$company', '$local', '$year', '$description')");
$target = "C:/xampp/htdocs/img/";
$target = $target . basename( $_FILES['file']['name']);
$Filename=basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
$conn =new mysqli("localhost", "root", "","test2");
$query = mysqli_query($conn,"INSERT INTO experience (image , PersonID) VALUES ('$Filename','$userid')");
print_r($query);
} else {
echo "Sorry, there was a problem uploading your file.";
}
how to send param and image in ajax ....As i can send only image separately and data separately in data . as i have try many different code but not working perfectly
var guestbookSendMessage = new FormData();
guestbookSendMessage.append('com',company);
guestbookSendMessage.append('loc', location);
guestbookSendMessage.append('year',year);
guestbookSendMessage.append('desc',des);
guestbookSendMessage.append('userid',userid);
guestbookSendMessage.append('file', $("#img")[0].files[0]);
$.ajax({
type : "POST",
url: "insert.php",
data : guestbookSendMessage,
cache: false,
contentType: false,
processData: false,
success: function (response){
}
});
this how its done.....

I am trying to change a background image of div using php and jquery.php variable not getting the value

I wrote the code for changing the background image of a div. I am able to upload the image and image is visible in the folder. The image path is getting uploaded in mysql database. But the image is not displaying as background in the div. The php variable value(location) for the specified path of image is not passing to the div. Can any one please let me know my mistake?
<?php
session_start();
include_once ('dataconnect.php');
$db_conx = mysqli_connect("localhost", "root", "", "productiondata");
$uid = $_SESSION['user_id'];
$username = $_SESSION['user_name'];
if (isset($_FILES['file'])) {
global $location;
$imagename = $_FILES["file"]["name"];
$imagepath = "images/";
$location = $imagepath . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], "$imagepath" . $_FILES["file"]["name"]);
$sql = "INSERT INTO image(user_id,imagepath,imagename) VALUES('$uid','$imagepath','$imagename')";
$query = mysqli_query($db_conx, $sql);
$sql1 = "SELECT * FROM image";
$query1 = mysqli_query($db_conx, $sql1);
while ($row = mysqli_fetch_array($query1)) {
$imagename = $row['imagename'];
$imagepath = $row['imagepath'];
echo $location;
}
}
jquery code
$('document').ready(function () {
$('.js_p-uploader').click(function () {
$('#file').click();
$('#file').change(function (e) {
e.preventDefault();
var blob = this.files[0];
var formData = new FormData();
formData.append('file', blob);
$.ajax({
url: "profile.php",
type: "POST",
data: formData,
mimeType: "multipart/form-data",
processData: false,
contentType: false,
success: function (location) {
}
});
});
});
});
div class="profile-cover-wrapper" style="background-image:url('?php echo
$location ;?');"input type="file" id="file" name ="file"
Returned data from an Ajax call cannot be used outside, or cannot be used as a PHP variable. What you can do is to change the src attribute of your <img> inside the success: function():
// AJAX CALL HERE
success: function(location) {
$('.profile-cover-wrapper').css("background-image", "url("+location+")");
}

upload array of files with ajax

I have form that allow me to submit text + number of files. the form submitted with AJAX.
Because it's a number of files my upload function give me error:
Warning: move_uploaded_file(images/usersFiles/14367317720-101.JPG) [function.move-uploaded-file]: failed to open stream: No such file or
directory in C:\Program Files
(x86)\wamp\www\new-site\func\global.func.php on line 134
line 134 is:
if (move_uploaded_file($files['file']['tmp_name'][$i], USER_FILES.$files['file']['name'][$i]))
files' var should be array (because I can load number of files).
How can I fix the error?
HTML:
<form class="form-horizontal" action='#' method="post" id="addCommentForm" enctype="multipart/form-data">
<textarea class="form-control" name="post[text]"></textarea>
<input type='file' name='file[]' class='multi form-control' maxlength='1' accept='gif|jpg|png|bmp' id="files"/>
<a class="btn btn-primary" id="submit">submit</a>
</form>
JS:
$(function() {
$("#submit").click(function() {
var file_data = $('#files').prop('files')[0];
var form_data = new FormData();
form_data.append('file[]', file_data);
var files_data = form_data;
var act = 'add';
form_data.append('act', act);
form_data.append('post[text]', $("#addCommentForm").find("textarea").val());
$.ajax({
type: "POST",
url: "ajax/addPost.php",
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data)
{
$('#commentsBox').html(data);
$("#addCommentForm")[0].reset();
}
});
return false; // avoid to execute the actual submit of the form.
});
});
server:
function upload_files ($ownerID, $msg, $files, $type)
{
$dateLX = get_current_linuxTime();
///////// Upload files //////////////
if(!empty($files))
{
foreach($files['file']['name'] as $i => $fileName)
{
$fileSurffix = pathinfo ($_FILES['file']['name'][$i]);
$fileSurffix = $fileSurffix['extension'];
$files['file']['name'][$i] = str_replace(' ','',$files['file']['name'][$i]);
$files['file']['name'][$i] = $dateLX.$i."-".$ownerID.".".$fileSurffix;
$fileName = $files['file']['name'][$i];
if (move_uploaded_file($files['file']['tmp_name'][$i], USER_FILES.$files['file']['name'][$i]))
{
$uploadFilesQuery = "INSERT INTO `files` (ownerID, name, type)
VALUES('$ownerID', '$fileName', '$type')";
$res = mysql_query($uploadFilesQuery);
if (!$res)
$msg['error']['uploadFile'] = "error <br />".mysql_error();
}
elseif ($files['file']['error'][$i] != 4)
$msg['error']['uploadFile'] = "ERROR ";
}
}
return ($msg);
}
USER_FILES must be an absolute path like
"C:\Program Files (x86)\wamp\www\new-site\images\usersFiles\"

php mysql ajax register form with image upload

hello brothers i would like to ask you how can make a registration form with image upload(base64) usign php mysql ajax and this is a part of my code but it didn't work. i wish if you tell me the type of table row and give me the righ code to do this.
$("#dsubmit").click(function(){
var formData = new FormData(this);
demail=$("#demail").val();
dpassword=$("#dpassword").val();
dfirstname=$("#dfirstname").val();
dlastname=$("#dlastname").val();
dtel=$("#dtel").val();
dadr=$("#dadr").val();
dspeciality=$("#dspeciality").val();
dcodepost=$("#dcodepost").val();
$.ajax({
type: "POST",
url: "inc/regdoc.php",
data: formData,"&demail="+demail+"&dpassword="+dpassword+"&dfirstname="+dfirstname+"&dlastname="+dlastname+"&dtel="+dtel+"&dadr="+dadr+"&dspeciality="+dspeciality+"&dcodepost="+dcodepost,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(html){
if(html=='true') {
$("#dmsg_box_connexion").css("color","green");
$("#dmsg_box_connexion").html("Utilisateur Ajouté avec succés ! Redirection ...");
window.setTimeout(function(){window.location.href = "index.php";}, 5000);
} else {
$("#dmsg_box_connexion").html("S'il vous plaît remplir tous les champs");
}
},
beforeSend:function() {
if((demail == "")||(dfirstname == "")||(dlastname == "")||(dtel == "")||(dpassword == "")||(document.getElementById("dfile").value == "")||(dcodepost == "")||(dadr == "")) {
$("#dmsg_box_connexion").css("color","red");
$("#dmsg_box_connexion").html("Tous Les Champs Sont Obligatoires !");
return false;
}
$("#dmsg_box_connexion").css("clor", "#32b1d3");
$("#dmsg_box_connexion").html("Validation...");
}
});
return false;
});
});
and this is the php file :
session_start();
$email = addslashes(htmlentities($_POST["demail"]));
$password = addslashes(htmlentities($_POST["dpassword"]));
$firstname = addslashes(htmlentities($_POST["dfirstname"]));
$lastname = addslashes(htmlentities($_POST["dlastname"]));
$codepost = addslashes(htmlentities($_POST["dcodepost"]));
$adresse = addslashes(htmlentities($_POST["dadr"]));
$tel = addslashes(htmlentities($_POST["dtel"]));
$speciality = addslashes(htmlentities($_POST["dspeciality"]));
$get_content = file_get_contents($_FILES['dfile']['tmp_name']);
$escape = mysql_real_escape_string($get_content);
$sourcePath = $_FILES['dfile']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "uploads/".$_FILES['dfile']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
$pass = sha1($password);
include ('pgs/config.php');
$insert = $bdd->query("INSERT INTO tbl_docs VALUES ('','$firstname','$lastname','$tel','$adresse','$speciality','$email','$pass','$escape','1','$codepost')");
if($insert == 1) {
echo 'true';
} else {
echo 'false';
}
and this is th form header:
<form id="d" method="post" action="#inc/regdoc.php" enctype="multipart/form-data">
Check the working example i have implemented in my project how to submit a form with image and some data fields.
$(document).on('submit', '#catcategory-form', function(event) {
event.preventDefault();
$.ajax({
url: "product.php",
method: 'POST',
data: new FormData(this),
dataType: 'json',
contentType: false,
processData: false,
success: function(infodata) {
if(infodata=='true'){
//do the stuff whatever you want
}
});
});
The another option you can do with image upload is convert base64. What you have to do is convert you form image in base 64 and send it on onChange event to the php and upload it in a file and keep the unique name in your database
//Call this function after getting base64 by post
$imageBase64=$_POST['image_converted_base64'];//get base64 of image from client end
$unique_name =uploadSingleImage($imageBase64);//function call
//function to upload image and get an unique name to store in db
function uploadSingleImage($base64) {
$uniname = uniqid() . date("Y-m-d-H-i-s") . ".jpg";
$new_image_url = "../../image/" . $uniname;
$base64 = 'data:image/jpeg;base64,' . $base64;
$base64 = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $base64));
file_put_contents($new_image_url, $base64);
return $uniname;
}
$sql = "INSERT INTO `table1`(image_name) VALUES('$unique_name')";
$conn->query($sql);

Not able to upload image via jquery, ajax and PHP

I have fair knowledge of JS, PHP and Ajax but this simple problem has driven me nuts.
I am trying to upload an image silently, without using a form. I am not using a form because that will lead to nested forms in my HTML, which I read, can cause additional issues.
I have been able to use oFReader, to preview the images.
To upload the image, I am attempting an AJAX call as given below:
HTML
<div id="loginButton2">
<div id="personalimg" >
<img src="photos/seller_photos/<?php echo $profile_pic; ?>" width="70" hight="70" />
</div>
</div>
<div id="loginBox2" style="display:none">
<div id="loginForm2" class="floatLeft" >
<fieldset>
<input id="file" type="file" name="profile_img" value="photos/seller_photos/<?php echo $profile_pic;?>"/>
<input id="file_submit" type="hidden" name="submit4" value="1" >
</fieldset>
</div>
</div>
JS
$('#file').change(function(){
var oFReader = new FileReader();
oFReader.readAsDataURL(this.files[0]);
var fd = new FormData();
var file = $("#file").prop("files")[0];
fd.append('profile_img', file);
fd.append('submit4', 1);
fd.append('filename', 1);
oFReader.onload = function (oFREvent) {
$.ajax({
url: "upload.php",
dataType: 'image',
cache: false,
contentType: false,
processData: false,
type: "POST",
data: fd,
success: function(data){
console.log(data);
},
error: function(){
console.log("image upload failed");
}
});
$('#loginForm2').toggle();
$('#personalimg').html('<img src="'+oFREvent.target.result+'" width="70" height="70">');
};
});
PHP
if(isset($_POST['submit4'])) {
$check_sql = "select profile_pic from profile where user_id=$user_id";
$check_rs = mysql_query($check_sql);
$check_num = mysql_num_rows($check_rs);
if($check_num==0) {
$sql = "insert into profile(user_id) values($user_id)";
$rs = mysql_query($sql);
}
$fName = $_FILES["profile_img"]["name"] ;
$data = explode(".", $fName);
$fileName = $user_id.'.'.$data[1];
if($fName!='')$user->update('profile_pic',$fileName);
$fileTmpLoc= $_FILES["profile_img"]["tmp_name"];
//image store path
$pathAndName = "photos/seller_photos/".$fileName;
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
if(move_uploaded_file) {
$response['status'] = '1';
header('Location: edit_profile_new.php');
} else {
$response['status'] = '0';
}
return $response;
}
But somehow, I have not been able to get this to work. I am using chrome. I get 302 Found status code and "image upload failed" in console.
Can someone please help me out?
ps: I know, mysql is deprecated and will migrate to pdo. This code is inherited and hence has old standards.

Categories