Different image upload form in one page - php

I've made simple PHP & MySQL crud with two image upload button to save two image to one database in different column like:
It works fine with one upload one image and saved to database, but when I add another button to try upload two image there's no error and it cannot storred in database.
Here is my small code:
<?php
include 'connection.php';
$temp = "upload/";
if (!file_exists($temp))
mkdir($temp);
$name = $_POST['name'];
$address = $_POST['address'];
$fileupload = $_FILES['fileupload']['tmp_name'];
$ImageName = $_FILES['fileupload']['name'];
$ImageType = $_FILES['fileupload']['type'];
if (!empty($fileupload)){
$random = rand(11111111, 99999999);
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt); // Extension
$ImageName = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
$NewImageName = str_replace(' ', '', $random.'.'.$ImageExt);
move_uploaded_file($_FILES["file_upload"]["tmp_name"], $temp.$NewImageName);
$query = "INSERT into table_fileupload (name, address, image_1, image_2) VALUES (?, ?, ?, ?)";
$dewan1 = $db1->prepare($query);
$dewan1->bind_param("sss", $name, $address, $NewImageName, $NewImageName);
$dewan1->execute();
echo "Success!";
} else {
echo "Error!";
}
?>
HTML:
<form id="form-data">
........................
........................
........................
<div class="form-group">
<label>image 1</label>
<input type="file" name="fileupload" id="fileupload" class="form-control" />
</div>
<div class="form-group">
<label>image 2</label>
<input type="file" name="fileupload" id="fileupload" class="form-control" />
</div>
<div class="form-group">
<input type="button" name="save" id="save" value="Save" class="btn btn-info mt-3" />
</div>
</form>
........................................
.......................................
<script src="js/jquery.min.js"></script>
<script>
$(document).ready( function () {
$("#save").click(function(){
const fileupload = $('#fileupload').prop('files')[0];
let formData = new FormData();
formData.append('fileupload', fileupload);
formData.append('name', $('#name').val());
formData.append('address', $('#address').val());
$.ajax({
type: 'POST',
url: "upload.php",
data: formData,
cache: false,
processData: false,
contentType: false,
success: function (msg) {
alert(msg);
document.getElementById("form-data").reset();
},
error: function () {
alert("Upload Error!");
}
});
});
});
</script>
How to solve this problem?

Related

How to upload multiple files using Jquery/Ajax

I m trying to upload two different files using Jquery and Ajax along with a text box.
However I can able to upload a single file and textbox using the code I have, but when I try to add another input type file, it breaks and doesn't upload any.
The code for single input type file I have: (upload fine)
test.php
<form method="post" action="" enctype="multipart/form-data" id="myform">
<div class='preview'><p class="temp"></p></div>
<div >
<input type="text" id="title" name="title" />
<input type="file" id="image" name="image" />
<input type="file" id="image" name="image2" />
<input type="button" class="button" value="Upload" id="but_upload">
</div>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
var files = $('#image')[0].files;
var title = $("#title").val();
fd.append('image',files[0]);
fd.append('title',title);
$.ajax({
url:'test2.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$(".temp").html(response);
$('.preview').show();
}else{
alert('File not uploaded');
}
}
});
});
});
</script>
test2.php
<?php
/* Getting file name */
$filename = $_FILES['image']['name'];
$title = $_POST['title'];
/* Location */
$location = "images-main/post-images/".$filename;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);
$imageFileType = strtolower($imageFileType);
/* Valid extensions */
$valid_extensions = array("jpg","jpeg","png");
$response = 0;
/* Check file extension */
if(in_array(strtolower($imageFileType), $valid_extensions)) {
/* Upload file */
if(move_uploaded_file($_FILES['image']['tmp_name'],$location)){
$response = $title;
}
}
echo $response;
exit;
The code for multiple input type file I have: (doesn't upload anything)
test.php
<form method="post" action="" enctype="multipart/form-data" id="myform">
<div class='preview'><p class="temp"></p></div>
<div >
<input type="text" id="title" name="title" />
<input type="file" id="image" name="image" />
<input type="file" id="image" name="image2" />
<input type="button" class="button" value="Upload" id="but_upload">
</div>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
var files = $('#image')[0].files;
var filess = $('#image')[1].filess;
var title = $("#title").val();
fd.append('image',files[0]);
fd.append('image2',filess[0]);
fd.append('title',title);
$.ajax({
url:'test2.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$(".temp").html(response);
$('.preview').show();
}else{
alert('File not uploaded');
}
}
});
});
});
</script>
test2.php
<?php
/* Getting file name */
$filename = $_FILES['image']['name'];
$filename2 = $_FILES['image2']['name'];
$title = $_POST['title'];
/* Location */
$location = "images-main/post-images/".$filename;
$location2 = "images-main/post-images/".$filename2;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);
$imageFileType = strtolower($imageFileType);
/* Valid extensions */
$valid_extensions = array("jpg","jpeg","png");
$response = 0;
/* Check file extension */
if(in_array(strtolower($imageFileType), $valid_extensions)) {
/* Upload file */
if(move_uploaded_file($_FILES['image']['tmp_name'],$location)){
if(move_uploaded_file($_FILES['image2']['tmp_name'],$location2)){
$response = $title;
}
}
}
echo $response;
exit;
Any help is greatly appreciated...
This works fine. Thanks to #CBroe:
Here what did the trick.
test.php
<form method="post" action="" enctype="multipart/form-data" id="myform">
<div class='preview'><p class="temp"></p></div>
<div >
<input type="text" id="title" name="title" />
<input type="file" id="image" name="image" />
<input type="file" id="video" name="video" />
<input type="button" class="button" value="Upload" id="but_upload">
</div>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
var files = $('#image')[0].files;
var filess = $('#video')[0].files;
var title = $("#title").val();
fd.append('image',files[0]);
fd.append('video',filess[0]);
fd.append('title',title);
$.ajax({
url:'test2.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$(".temp").html(response);
$('.preview').show();
}else{
alert('File not uploaded');
}
}
});
});
});
</script>
test2.php
<?php
/* Getting file name */
$filename = $_FILES['image']['name'];
$filename2 = $_FILES['video']['name'];
$title = $_POST['title'];
/* Location */
$location = "images-main/post-images/".$filename;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);
$imageFileType = strtolower($imageFileType);
$location2 = "images-main/post-images/".$filename2;
$imageFileType2 = pathinfo($location2,PATHINFO_EXTENSION);
$imageFileType2 = strtolower($imageFileType2);
/* Valid extensions */
$valid_extensions = array("jpg","jpeg","png");
$response = 0;
/* Upload file */
if(move_uploaded_file($_FILES['video']['tmp_name'],$location2)){
$response = $title;
}
if(move_uploaded_file($_FILES['image']['tmp_name'],$location)){
$response = $title;
}
echo $response;
exit;

CSV File not uploading through php and jquery(ajax)

I am trying to upload a csv file using this code but the file directory is not getting uploaded to the folder and i cannot see any error in the code.
Please help me in this.
HTML code:
<form method="POST" action="submit.php" enctype="multipart/form-data"">
<input type="file" name="file" id="upload"><br>
</form>
JQUERY AJAX code:
$(document).ready(function(){
$('#upload').on('change', function(e) {
e.preventDefault();
var file=this.files[0];
console.log(file);
var filename = file.name;
var ext = filename.split('.')[1];
if(ext == "csv"){
FileUploadAjaxCall();
}else{
$("#fileMsg").html("Extension not valid:Try Again");
}
});
});
function FileUploadAjaxCall(){
$.ajax({
url:'submit.php',
type:'POST',
data:new FormData($('#upload').get(0)),
contentType:false,
cache:false,
processData:false,
success:function(data){
if(data == 1){
console.log("File Uploaded Successfully");
}else{
console.log(data);
console.log("Error");
}
}
});
}`
PHP code:
<?php
$file = $_FILES['file'];
$filename = $_FILES['file']['name'];
$filetmpname = $_FILES['file']['tmp_name'];
$fileDes = 'uploads/'.$filename;
$t = move_uploaded_file($filetmpname,$fileDes);
if($t == true){
echo 1;
};
?>
I have re-written your code as follows. Its always good to validate files upload at server backend and javascript validation can be fooled.
Try the code below and let me see what happens
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload_processor.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
$("#errorLayer").html(data);
},
error: function()
{
}
});
}));
});
</script>
</head>
<body>
<div>
<form id="uploadForm" action="upload_processor.php" method="post">
<div id="targetLayer"></div>
<div id="errorLayer"></div>
<div id="uploadFormLayer">
<input name="file" type="file" class="inputFile" /><br/>
<input type="submit" value="Submit" class="btnSubmit" />
</form>
</div>
</div>
</body>
</html>
<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['file']['tmp_name'])) {
$fileName = $_FILES['file']['name'];
$sourcePath = $_FILES['file']['tmp_name'];
$targetPath = "uploads/".$_FILES['file']['name'];
if($fileName ==''){
echo "<div id='errorLayer'>Please select file</div>";
exit;
}
$fileType = pathinfo($fileName, PATHINFO_EXTENSION);
$allowTypes = array('csv');
if (!in_array($fileType, $allowTypes, true)) {
echo "<div id='errorLayer'>File type is invalid. Only CSV is allowed</div>";
exit;
}
if(move_uploaded_file($sourcePath,$targetPath)) {
echo "<div id='targetLayer'>File uploaded successfully</div>";
?>
<?php
}
}
}
?>
//form.html
<form method="POST" action="submit.php" id="uploadForm">
<input type="file" name="file" id="upload" accept=".csv"><br>
<input type="submit">
</form>
<div id="fileMsg"></div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function(e){
$('#uploadForm').on('submit', function(e) {
e.preventDefault();
$.ajax({
url:'submit.php',
type:'POST',
data:new FormData(this),
contentType:false,
cache:false,
processData:false,
success:function(){
$("#fileMsg").html("File Uploaded Successfully");
},
error:function(){
//$("#fileMsg").html(data);
$("#fileMsg").html("Error");
}
});
});
});
</script>
//submit.php
<?php
// $file = $_FILES['file'];
$filename = $_FILES["file"]["name"];
$filetmpname = $_FILES["file"]["tmp_name"];
$fileDes = "uploads/".$filename;
$t = move_uploaded_file($filetmpname,$fileDes);
if($t == true){
echo "1";
};
?>
u can do it like this

how to upload image on server using ajax in cordova build

Can anybody provide the complete ajax and (php or asp) server side code to upload the image directly from simple html to online server.
Actually I'm trying to upload image on server using phonegap cli
<form id="uploadaadhar" action="http://server_url" method="post">
<input type="hidden" name="userid" >
<br><label>Aadhar Number</label>
<br><input type="number" name="aadhar" class="form-control" placeholder="XXXX XXXX XXXX">
<br><label>Choose File</label>
<br><input name="files[]" class="form-control" type="file" />
<br><label>PAN Number</label>
<br><input type="number" name="pan" class="form-control" placeholder="XXXX XXXX XXXX">
<br><span class="ak-text-indigo">Leave Pan Card Field Blank if you do not want to update your pan card</span>
<br><br>
<input type="submit" value="Upload" class="ak-btn ak-blue">
</form>
<script>
$("[type='hidden']").val(localStorage.getItem("userid"));
$("#uploadaadhar").ajaxForm(function(data){
if(data !== ""){
$("[type='submit']").val(data);
}
});
</script>
Here is a sample demo for uploading image.
Here data is image and other data that you want to send using post.
url is where you want to post data.
<html>
<form>
<input id="file-input" type="file" name="files" accept="image/*" />
<button type="button" onclick="uploadImage()">upload</button>
</form>
</html>
and ajax function
function uploadImage(){
url = "your web url where u want to upload image";
var formdata = new FormData();
formdata.append( 'files', $('#file-input')[0].files[0]);
$.ajax({
type: "POST",
url: url,
data: formdata,
processData: false,
contentType: false,
type: 'POST',
success: function(msg){
// on success
},
error: function(){
alert("failure");
},
async: false
});
}
<form id="uploadaadhar" action= "http://app.365valueservices.com/365APP/settings.php" method="post">
<label>Aadhar Number</label>
<input type="number" name="aadhar" class="form-control" placeholder="XXXX XXXX XXXX">`enter code here`
<label>Choose File</label>
<input name="files[]" class="form-control" type="file" />
<input type="submit" value="Upload" class="ak-btn ak-blue">
</form>
Javascript
<script> $("#uploadaadhar").ajaxForm(function(data){
if(data !== ""){
$("[type='submit']").val(data);
} });
</script>
if(isset($_FILES['files']))
{
if(is_array($_FILES))
{
foreach ($_FILES['files']['name'] as $name => $value)
{
$file_name = explode(".", $_FILES['files']['name'][$name]);
$allowed_ext = array("jpg","JPG", "jpeg", "JPEG", "png", "PNG", "gif","pdf","docx","doc");
if(in_array($file_name[1], $allowed_ext))
{
$new_name = md5(rand()) . '.' . $file_name[1];
$sourcePath = $_FILES['files']['tmp_name'][$name];
$targetPath = "../httpdocs/docs/".$new_name;
//$targetPath = "upload/".$new_name;
move_uploaded_file($sourcePath, $targetPath);
$filepath = "../docs/".$new_name;
$sql = "update usertbl set aadhar = '".$_POST['aadhar']."' where userid = ".$_POST['userid'];
sqlsrv_query($conn,$sql);
if($_POST['pan'] != ""){
$sql2 = "update usertbl set panno = '".$_POST['pan']."' where userid = ".$_POST['userid'];
sqlsrv_query($conn,$sql2);
}
$stmt = sqlsrv_query($conn,"select * from user_meta where userid = ".$_POST['userid']." and metakey = 'aadharpath'");
$row_count = sqlsrv_has_rows($stmt);
if($row_count === false){
sqlsrv_query($conn,"insert into user_meta(userid,metakey,metavalue,Active) values (".$_POST['userid'].",'aadharpath','".$filepath."',1)");
}
else
{
sqlsrv_query($conn,"update user_meta set metavalue = '".$filepath."' where metakey='aadharpath' and userid=".$_POST['userid']);
}
sqlsrv_query($conn,"insert into useractivity values(".$_POST['userid'].",'You had updated your aadhar details','" .date("d-m-Y H:i:s"). "',1)");
echo "Updated Successfully";
}
}
}
}

Multiple file extension validation

I have an html form where i have input file array. What im trying to achieve is get the file array in php file loop through it and check if a file extension is correct else add it to array and then show as json array in ajax. Can someone help me? here is the code for the form:
<html>
<head>
<title>Multiple file upload handling</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#form").submit(function(e){
var file1 = $("#file1").val();
var file2 = $("#file2").val();
$("#results").text("");
var results = $("#results");
if(file1 == "" || file2 == ""){
results.text("File 1 and File 2 are empty.");
}else {
var formarray = new FormData($("#form")[0]);
$.ajax({
url: "upload.php",
type: "POST",
dataType: "JSON",
enctype: 'multipart/form-data',
async: false,
cache: false,
contentType: false,
processData: false,
data: formarray,
success:function(response){
if(response.success == false){
$(response.message).each(function(index, value){
results.append("<li id="+ index + ">" + value + "</li>");
});
}else{
alert(response.message);
}
}
});
}
e.preventDefault();
});
})
</script>
</head>
<body>
<form method="post" role="form" enctype="multipart/form-data" id="form">
<input type="file" id="file1" name="file[]" style="margin-bottom:30px;"><br>
<input type="file" id="file2" name="file[]" style="margin-bottom:30px;"><br>
<input type="submit" id="upload" name="upload">
</form>
<div id="results"></div>
</body>
</html>
And below is the php code:
<?php
$filenames = $_FILES['file']['name'];
$filesizes = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$data = array();
$errors = array();
foreach($filenames as $key=>$value){
$filesize = $_FILES["file"]["size"][$key];
$filetype = $_FILES["file"]["type"][$key];
$file_tmpname = $_FILES["file"]["tmp_name"][$key];
$valid_extensions = array("jpeg", "jpg", "gif", "png");
$ext = explode(".", $value);
$extension = end($ext);
if(!in_array($extension, $valid_extensions)){
$errors[] = $value;
$data["success"] = false;
$data["message"] = $errors;
} else {
$data["success"] = true;
$data["message"] = "success";
move_uploaded_file($file_tmpname, "uploads/".$filename);
}
}
echo json_encode($data);
?>

Update Image from database using ajax, jquery,and PHP not working

I wanna update profile picture of user that has logged in to my website.
I use ajax, jquery, php to update data, in order to update data without refresh the page.
This code just working to upload image into folder, but when I use this code to update image from database, it only sent null into database.
jquery and ajax script
$("#form-ava").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "../config.inc/upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview-ava").html(data).fadeIn();
$("#form-ava")[0].reset();
$("#hidden-list").hide();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
And it's the php syntax
upload.php
<?php
require_once 'koneksi.php';
if($_POST)
{
$id_user= $_POST['id_user'];
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = '../images/ava/'; // upload directory
try {
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
// can upload same image using rand function
$final_image = rand(1000,1000000).$img;
// check's valid format
if(in_array($ext, $valid_extensions))
{
$path = $path.strtolower($final_image);
if(move_uploaded_file($tmp,$path))
{
echo "<img src='$path' />";
}
else
{
echo 'invalid';
}
$update = $db_con->prepare("UPDATE tb_users SET image=:img WHERE id_user=:id_user");
$update->bindparam(":id_user", $id_user);
$update->bindparam(":img", $image);
$update->execute();
$count = $update->rowCount();
if($count>0) {
echo "success";
}else {
echo "can't update!";
}
}
}catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
HTML syntax
<form id="form-ava" action="../config.inc/upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" id="id_user" name="id_user" value="<?php echo $row->id_user;?>">
<input id="ava-img" type="file" name="image" value="<?php echo $row->image;?>"/>
<input id="button" type="submit" value="Simpan" name="update"></br>
</i> Batal
</form>
<div id="err"></div>
<form id="form-ava" action="../config.inc/upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" id="id_user" name="id_user" value="<?php echo $row->id_user;?>">
<input id="ava-img" type="file" name="image" value="<?php echo $row->image;?>"/>
<input id="button" type="submit" value="Simpan" name="update"></br>
</i> Batal
</form>
<div id="err"></div>
<script type="text/javascript">
$("#form-ava").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "../config.inc/upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview-ava").html(data).fadeIn();
$("#form-ava")[0].reset();
$("#hidden-list").hide();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
</script>
I found two errors in your code in proses.php
<?php include 'koneksi.php';
$foto = #$_POST['foto'];
$id = #$_POST['id'];
$update = $db->prepare("UPDATE tb_users SET foto=:foto WHERE id=:id");
$update>bindParam(":id", $id);
$update->bindParam(":foto", $foto);
$update->execute();
if($update->rowCount() > 0) {
echo "success";
}
?>
the error messages would be very helpful, but at the very least you are missing a - in $update>bindParam(":id", $id);, so it should be $update->bindParam(":id", $id);
you did the same thing again with $update>rowCount() should be $update->rowCount()
update: I see you edited your question to fix those, but still haven't posted the errors you're receiving. Were those tpyos in your question, or are you progressively fixing your code?
still, it looks like you're missing a closing curly brace } in this statement:
if($update>rowCount() > 0) {
echo "success";
?>
also, why are you silencing notices with #$_POST? if those values are empty, then do you really want to be updating the table?

Categories