Hello,

In my project I have a form with many inputs and one object is using DropzoneJS to attach files.
Since I store all the inputs when I post the form I need somehow to read the file names of the uploaded files in my server,
currently I can only get the list of the original filename of the files that are uploaded.
For many reasons when a file is uploaded I am giving it a random name with time() function.

A part of my HTML form

<form id="appointment-form" class="box-body no-padding">
    <input name="firstname" type="text" />
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 no-padding">
        <div class="form-group">
            <form id="uploadInput" method="post" action="upload.php" class="dropzone">
                <div class="fallback">
                    <input name="file" type="file" />
                </div>
            </form>
        </div>
    </div>
  <button type="button" class="btn btn-default btn-flat">
     <i class="fa fa-plus"></i> Add
  </button>
</form>

upload.php

<?php
$ds          = DIRECTORY_SEPARATOR;
$storeFolder = 'files/tmp';

if (!empty($_FILES)) {
         $tempFile   = $_FILES['file']['tmp_name'];             
    $targetPath     = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
    $path_parts     = pathinfo($_FILES["file"]["name"]);
    $extension      = $path_parts["extension"];
    $targetFile     = $targetPath . time() . '.' . $extension;
    echo $targetFile;
    move_uploaded_file($tempFile, $targetFile);
}
?>

How can I store the $targetFile in my HTML form so I can read them when I post the main form?!

Dani AI

Generated

A few practical tips to make this robust and avoid the common gotchas:

  • Avoid nesting a Dropzone form inside another form. Nested forms are invalid HTML and can break submission. Use a single form, or make your drop area a div and set url in Dropzone (MDN form element).
  • Return only a JSON object with the stored filename (not an absolute server path). Ensure the response has Content-Type: application/json; otherwise the Dropzone success handler may receive a string, and accessing response.target_file will be undefined. If you still get a string, do response = JSON.parse(response).
  • Keep an array of filenames in JS and serialize it to a hidden input on submit; it is easier to add/remove than maintaining a comma-separated string. Also handle the removedfile event to keep the list in sync (Dropzone events).

For safer, collision-resistant filenames and basic server-side hygiene:

// upload.php (snippet)
$ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
$basename = bin2hex(random_bytes(16)) . ($ext ? ".$ext" : "");
$targetDir = __DIR__ . '/files/tmp/';
$targetFile = $targetDir . $basename;

if (!is_uploaded_file($_FILES['file']['tmp_name'])) { http_response_code(400); exit; }
if (!move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) { http_response_code(500); exit; }

header('Content-Type: application/json');
echo json_encode(['file' => $basename]);

Validate type/size server-side (e.g., finfo_file) and restrict allowed extensions; see move_uploaded_file, random_bytes, and OWASP’s File Upload Cheat Sheet. If you want client-side naming too, consider Dropzone’s renameFile option but keep the server as the source of truth.

Recommended Answers

All 4 Replies

In other words you want to return back the new name of the uploaded file? In the PHP script you can send a JSON response with the filename, so move line 12 to 11 and replace the echo with:

header('Content-type: application/json');
echo json_encode(['target_file' => $targetFile]);

and use the success event in DropzoneJS to get the response from the server:

Then use javascript to parse JSON and compile a list of uploaded files as (hidden) inputs... but start with something easier: print the response.

By the way, time() will not prevent overwrites.

I managed to change the code as suggest, for the moment it seems to be working.
All the uploaded images are storen in a hidden input divided by a ,

Here is a simple version of the code to help everyone else in the future

<form id="appointment-form" class="box-body no-padding">
    <input name="firstname" type="text" />
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 no-padding">
        <div class="form-group">
            <form id="uploadInput" method="post" action="upload.php" class="dropzone">
                <div class="fallback">
                    <input name="file" type="file" />
                </div>
            </form>
            <input name="attached_files" value="" type="hidden" />
        </div>
    </div>
  <button type="button" class="btn btn-default btn-flat">
     <i class="fa fa-plus"></i> Add
  </button>
</form>
<script type="text/javascript">
        jQuery(".dropzone").dropzone({
            success : function(file, response) {
                //console.log(file);
                //console.log(response);
                if (response['target_file'] != '') {
                    var currentValue = jQuery("#appointment-form input[name='attached_files'").val();
                    if (currentValue == '') {
                        jQuery("#appointment-form input[name='attached_files'").val(response['target_file']);
                    } else {
                        jQuery("#appointment-form input[name='attached_files'").val(currentValue + ", " + response['target_file']);
                    }
                }
            }
        });
    </script>

upload.php

<?php
    header('Content-type: application/json');
    $ds          = DIRECTORY_SEPARATOR;  //1
    $storeFolder = 'files/tmp';   //2
    if (!empty($_FILES)) {
        $tempFile       = $_FILES['file']['tmp_name'];      
        $targetPath     = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
        $path_parts     = pathinfo($_FILES["file"]["name"]);
        $extension      = $path_parts["extension"];
        $targetFile     = $targetPath . time() . '.' . $extension;
        move_uploaded_file($tempFile, $targetFile); //6
        echo json_encode(['target_file' => $targetFile]);
    }
?>

Thank you cereal :)

commented: you're welcome :) +15

hi bro! i used the above code given by you but on frontend in input value, its adding value 'undifined', can you please tell me how to fix it?

Hello,

With just this information I can't say exactly where may be your issue.
Can I ask you if dropzone JS has be called on your page?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.