0

I am running into the issue where the form input fields are not passing data along with the files when I try to integrate dropzone into my form. I need it to pass the additional fields as it contains info for the file name for the files. Here is what I have, if someone could please tell me what I am doing wrong. I have removed some folder/file names for security, I italiced those

Form Page:

<form action="upload_photos.php" method="post" enctype="multipart/form-data">
  <div class="form_quartercontent">
    <select name="fp_id" id="fp_id">
      <option value="*some option*" >*Option Label*</option> 
    </select> 
  </div>
  <div class="form_quartercontent">
    <input name="order_id" type="hidden" id="order_id" value="the order id #" />
  </div>
  <div class="clear"></div>
  <div class="dropzone" id="myDropzone"></div>
  <div class="form_quartercontent"><input name="submit-all" type="submit" class="form-submit-button" id="submit-all" value="Upload Photo" /></div></form>

<script>Dropzone.options.myDropzone= {
    url: 'upload_photos.php',
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 100,
    maxFiles: 100,
    maxFilesize: 3,
    acceptedFiles: 'image/*',
    addRemoveLinks: true,
    init: function() {
        var dzClosure = this; // Makes sure that 'this' is understood inside the functions below.

        // for Dropzone to process the queue (instead of default form behavior):
        document.getElementById("submit-all").addEventListener("click", function(e) {
            // Make sure that the form isn't actually being sent.
            e.preventDefault();
            e.stopPropagation();
            dzClosure.processQueue();
        });

        //send all the form data along with the files:
        this.on("sending", function(file, xhr, formData) { 

    //formData.append('task_name', jQuery('#task_name').val());

    $("form").find("input").each(function(){
      formData.append($(this).attr("name"), $(this).val());
  });
  
  });
    
   }
}
</script>

** Upload PHP:**

$order_photo = $_POST['order_id'];
$photo_fp = $_POST['fp_id'];

if(!empty($_FILES)){ 
    // Include the database configuration file 
    require("includes/*databaseconnection.php*");
    if(!($p_update = mysqli_query($link,"INSERT INTO *table* SET order_id='$order_photo',fp_id='$photo_fp'"))){
        printf("%s", sprintf("internal error %d:%s\n", mysqli_errno(), mysqli_error()));
        exit();
    }
    $photo_id = mysqli_insert_id($link); 
    $extension = strrchr($_FILES['file']['name'],'.'); 
    $extension = strtolower($extension); 
    $save_path = '*pathtofolder*/'. $order_photo .'/*storingfolder*/'; 
    if(!is_dir($save_path)) mkdir($save_path);
    $filename = $save_path . $order_photo ."_". $photo_fp."_". $photo_id . $extension; 
    move_uploaded_file($_FILES['file']['tmp_name'],$filename);
     
} 
TheOTech
  • 11
  • 4
  • 1
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Jan 20 '23 at 11:55
  • 1
    You have an error. [`mysqli_error()`](https://www.php.net/manual/en/mysqli.error.php) needs one argument. Please consider switching error mode on instead. [How to get the error message in MySQLi?](https://stackoverflow.com/a/22662582/1839439) – Dharman Jan 20 '23 at 11:55

2 Answers2

0

This is my working solution:

Form Page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>upload Files</title>
    <script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
    <script src="https://unpkg.com/dropzone@5/dist/min/dropzone.min.js"></script>
<link
  rel="stylesheet"
  href="https://unpkg.com/dropzone@5/dist/min/dropzone.min.css"
  type="text/css"
/>
</head>
<body>

<form action="upload_photos.php" method="post" enctype="multipart/form-data">
<div class="form_quartercontent">
<select id="fp_id" name="fp_id">
    <option value="200">200</option> 
    <option value="300">300</option> 
</select> 
</div>
<div class="form_quartercontent">
    <input name="order_id" type="hidden" id="order_id" value="1" />
</div>
<div class="clear"></div>
<div class="dropzone" id="myDropzone"></div>
<div class="form_quartercontent">
    <input name="submit-all" type="submit" class="form-submit-button" id="submit-all" value="Upload Photo" />
</div>
</form>
<script>Dropzone.options.myDropzone= {
url: 'upload_photos.php',
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
maxFilesize: 3,
acceptedFiles: 'image/*',
addRemoveLinks: true,
init: function() {        
    var dzClosure = this;
    document.getElementById("submit-all").addEventListener("click", function(e) {
        e.preventDefault();
        e.stopPropagation();
        dzClosure.processQueue();
    });
    this.on("sending", function(file, xhr, formData) { 
        $("form").find("input").each(function(){
            formData.append($(this).attr("name"), $(this).val());
        });
        $("form").find("select").each(function(){
            formData.append($(this).attr("name"), $(this).val());
        });
        
    });
    this.on("success", function(file, serverFileName) {
        var sfn = serverFileName

    this.on("removedfile", function(file) {
        $.post("deleteFiles.php", { "file_name" : sfn },function(data){
            alert('File has been successfully deleted')
        });
    });
    });
  
}
}
</script>
</body>
</html>

upload_photos.php:

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('database_server', 'username', 'password', 'database_name');
if($_FILES['file'] && $_POST['submit-all']){ 
    $order_photo = $_POST['order_id'];
    $photo_fp = $_POST['fp_id'];
    $stmt = $mysqli->prepare("INSERT INTO files(order_id, fp_id) VALUES (?, ?)");
    $stmt->bind_param("ss", $order_photo, $photo_fp);
    $stmt->execute();
    $photo_id = $stmt->insert_id;
    $save_path = sprintf("files/%s/sortingFolder/", $order_photo); 
    if(!is_dir($save_path))
    {
        mkdir('files');
        mkdir(sprintf("files/%s",$order_photo));
        mkdir(sprintf("files/%s/sortingFolder",$order_photo));
    } 
    $count = count($_FILES['file']['name']);
    for($i=0; $i < $count; $i++ )
    {
        $fileName[] = mb_strtolower(basename($_FILES['file']['name'][$i]),'UTF-8');
        $extension[] = pathinfo($fileName[$i], PATHINFO_EXTENSION);
        $makeHash[] = hash('sha1',date('YmdHis').mt_rand(100,999));
        $fileNewName[] = sprintf($save_path . $order_photo . "_"  . "%s" . "_". $photo_id ."_". $makeHash[$i] . "." . $extension[$i],$photo_fp); 
        move_uploaded_file($_FILES['file']['tmp_name'][$i],$fileNewName[$i]);
        print $fileNewName[$i];

    }
} 
?>

deleteFiles.php:

<?php
header("Content-Type: application/json; charset=UTF-8");
$data['fileName'] = $_POST['file_name'];
unlink($data['fileName']);
print json_encode($data);
?>

my database structure: view image

ramin
  • 448
  • 4
  • 15
  • I replaced the coding and still not functioning. Error log shows PHP Warning: mysqli_query() expects parameter 1 to be mysqli, null given – TheOTech Jan 20 '23 at 14:07
  • @TheOTech ,I updated it. it is worked for me. – ramin Jan 20 '23 at 15:53
  • Thanks for the help, got it now. The only issue I had was I have my order_id and fp_id set as int in my database. Had to change =$_POST to =(int)_$POST – TheOTech Jan 21 '23 at 15:01
  • @TheOTech I updated it again and made it more secure(prepared statements). If you are satisfied, please confirm my answer as the correct answer. – ramin Jan 21 '23 at 15:24
0

You could have also used the formData.append("variableName", "valueOfVariable") and in your *.php file just read the $_POST['variableName']. This way you can get rid of $("form").find("input") functions.

helvete
  • 2,455
  • 13
  • 33
  • 37