Solved

Could you point a path on how to deal with PHP/ Dropzone to upload files and to obtain the file names to be saved in database?

Posted on 2016-10-25
13
103 Views
Last Modified: 2016-10-31
Hi Experts

Could you point a path on how to deal with PHP/ Dropzone to upload files and to obtain the file names to be saved in database?

Thanks in advance!
0
Comment
Question by:Eduardo Fuerte
  • 6
  • 4
  • 2
  • +1
13 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Is this what you're looking at?
http://www.dropzonejs.com/

If so, it uses a regular PHP action script, the kind that deals with input type=file
0
 
LVL 32

Expert Comment

by:Big Monty
Comment Utility
check out this tutorial, example shows how to handle multiple uploaded files:

http://php.net/manual/en/features.file-upload.post-method.php#example-354
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
That's exactly where the "Basic PHP File Upload" link in the DropZone.js documentation points!
http://www.php.net/manual/en/features.file-upload.post-method.php#example-354
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
In experimenting with this thing, it appears to make a request to the action script, but there is no data in $_POST, only in $_FILES.  It looks like it makes the request as soon as the file is dropped into the active area.  The name associated with the file is the basename in the directory that contains the file.  So it looks like it's up to you to choose the server-side directory, etc.

Here's an example of what your script will find in $_FILES after a successful drag-n-drop.
(
    [file] => Array
        (
            [name] => too_hard.png
            [type] => image/png
            [tmp_name] => /tmp/phpkk4RGx
            [error] => 0
            [size] => 10048
        )

)

Open in new window

0
 

Author Comment

by:Eduardo Fuerte
Comment Utility
Hi

What I did in the meanwhile is:

View code
// Declare the class dropzone at the form
<!-- Begin: Form Edit -->
<form method="post" action="#" id="entity-form" enctype="multipart/form-data"  class="dropzone">
....

//Important to be file[] since it's multiple files
 <input name="file[]" type="file" multiple />  

Open in new window


The modal has a controller (it's the action script in this case) - when saving the data, using code obtained at Dropzone example

public function save()
    {
        try {

            $data = $this->input->post();

            $ds = DIRECTORY_SEPARATOR; //1
            $storeFolder = print base_url() . 'public/uploads/anexos/';

            if (!empty($_FILES)) {
                $tempFile = $_FILES['file']['tmp_name']; //3
                $targetPath = dirname(__file__) . $ds . $storeFolder . $ds; //4
                $targetFile = $targetPath . $_FILES['file']['name']; //5
                move_uploaded_file($tempFile, $targetFile); //6
            }

			....

Open in new window

Just one error I'm having at this point:
img006
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 100 total points
Comment Utility
This seems to work correctly as an action= script.  I copied the example JS and CSS to my server in order to test it.  I'm not going to leave this on my server, but hopefully the code example will help you get started!
<?php // demo/dropzone_upload_example.php
/**
 * https://www.experts-exchange.com/questions/28978754/Could-you-point-a-path-on-how-to-deal-with-PHP-Dropzone-to-upload-files-and-to-obtain-the-file-names-to-be-saved-in-database.html
 * Demonstrate how to upload one or more files, using DropZone.js and PHP
 *
 * For each request $_FILES looks like this:
 *
 *  [file] => Array
 *  (
 *     [name] => too_hard.png
 *     [type] => image/png
 *     [tmp_name] => /tmp/phpkk4RGx
 *     [error] => 0
 *     [size] => 10048
 *  )
 *
 * http://www.dropzonejs.com/#server-side-implementation
 * http://www.php.net/manual/en/features.file-upload.post-method.php#example-354
 */
error_reporting(E_ALL);

// ESTABLISH THE NAME OF THE DESTINATION FOLDER ('storage' DIRECTORY)
$storage = 'storage';
if (!is_dir($storage))
{
    mkdir($storage);
}

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE WILL ACCEPT
$file_exts = array
( 'jpg'
, 'gif'
, 'png'
)
;

// ARRAY OF ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( UPLOAD_ERR_OK         => "Success!"
, UPLOAD_ERR_INI_SIZE   => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, UPLOAD_ERR_FORM_SIZE  => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, UPLOAD_ERR_PARTIAL    => "The uploaded file was only partially uploaded"
, UPLOAD_ERR_NO_FILE    => "No file was uploaded"
, 5                     => "UNDEFINED ERROR #5"
, UPLOAD_ERR_NO_TMP_DIR => "Missing a temporary folder"
, UPLOAD_ERR_CANT_WRITE => "Cannot write file to disk"
, UPLOAD_ERR_EXTENSION  => "A PHP extension stopped the file upload"
)
;

// IF WE HAVE GOT SOMETHING IN $_FILES - RUN THE ACTION SCRIPT
if (!empty($_FILES['file']))
{
    $my_uploaded_file = $_FILES['file'];

    // SKIP OVER EMPTY REQUESTS - NOTHING UPLOADED
    $error_code = $my_uploaded_file["error"];
    if ($error_code == UPLOAD_ERR_NO_FILE) exit;

    // IF THERE ARE ERRORS
    if ($error_code != UPLOAD_ERR_OK)
    {
        $error_message = $errors[$error_code];
        trigger_error("Upload error code: $error_code: $error_message", E_USER_ERROR);
    }

    // SYNTHESIZE THE NEW FILE NAME
    $f_type = explode('.', basename($my_uploaded_file['name']));
    $f_type = end($f_type);
    $f_type = trim(strtolower($f_type));

    $f_name = explode('.', basename($my_uploaded_file['name']));
    $f_name = current($f_name);
    $f_name = trim(strtolower($f_name));

    // SERVER PATH TO THE NEW FILE
    $my_file_path
    = getcwd()
    . DIRECTORY_SEPARATOR
    . $storage
    . DIRECTORY_SEPARATOR
    . $f_name
    . '.'
    . $f_type
    ;

    // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
    if (!in_array($f_type, $file_exts))
    {
        trigger_error("$f_type Not allowed", E_USER_ERROR);
    }

    // TRY TO SAVE THE FILE
    if (!move_uploaded_file($my_uploaded_file['tmp_name'], $my_file_path))
    {
        trigger_error("PHP move_uploaded_file() failed for $my_file_path", E_USER_ERROR);
    }

    // TRY TO SET THE FILE PERMISSIONS
    if (!chmod ($my_file_path, 0755))
    {
        trigger_error("chmod(0755) failed for $my_file_path", E_USER_ERROR);
    }
} // END ACTION SCRIPT


// CREATE THE HTML FORM USING HEREDOC NOTATION
$form = <<<EOF
<!DOCTYPE html>
<meta charset="utf-8">
<title>Dropzone simple example</title>
<!--
  DO NOT SIMPLY COPY THOSE LINES. Download the JS and CSS files from the
  latest release (https://github.com/enyo/dropzone/releases/latest), and
  host them yourself!
-->
<script src="dropzone.js"></script>
<link rel="stylesheet" href="dropzone.css">

<p>
  This is the most minimal example of Dropzone.
</p>

<!-- Change /upload-target to your upload address -->
<form action="https://iconoun.com/demo/dropzone_upload_example.php" class="dropzone"></form>
EOF;

echo $form;

Open in new window

0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 51

Accepted Solution

by:
Julian Hansen earned 400 total points
Comment Utility
Lets break this down
From the HTML
<input name="file[]" type="file" multiple />

Open in new window

So we are sending through an array of files
What does that look like
Consider the following
HTML
<form method="post" action="reflect.php" enctype="multipart/form-data">
  <input name="file[]" type="file" multiple /> 
  <input type="submit">
</form>

Open in new window

Reflect.php
<pre>
<?php
print_r($_FILES);
?>
</pre>

Open in new window

You can see it working here
Select a couple of files and see what we get back
Array
(
    [file] => Array
        (
            [name] => Array
                (
                    [0] => pic1 - Copy.png
                    [1] => pic2 - Copy.png
                    [2] => oren - Copy.png
                    [3] => cta-get-more-information-over - Copy.png
                )

            [type] => Array
                (
                    [0] => image/png
                    [1] => image/png
                    [2] => image/png
                    [3] => image/png
                )

            [tmp_name] => Array
                (
                    [0] => C:\Windows\Temp\phpACD3.tmp
                    [1] => C:\Windows\Temp\phpACD4.tmp
                    [2] => C:\Windows\Temp\phpACD5.tmp
                    [3] => C:\Windows\Temp\phpACD6.tmp
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                    [2] => 0
                    [3] => 0
                )

            [size] => Array
                (
                    [0] => 181
                    [1] => 248
                    [2] => 478
                    [3] => 679
                )

        )
)

Open in new window

From this we can deduce that
$tempFile = $_FILES['file']['tmp_name']; //3

Open in new window

Refers to this component of the returned data
            [tmp_name] => Array
                (
                    [0] => C:\Windows\Temp\phpACD3.tmp
                    [1] => C:\Windows\Temp\phpACD4.tmp
                    [2] => C:\Windows\Temp\phpACD5.tmp
                    [3] => C:\Windows\Temp\phpACD6.tmp
                )

Open in new window

Which is in fact an array
From the above we can see that to access the files that we want we have to put the processing inside a loop
foreach($_FILES['file']['tmp_name'] as $key => $tempFile) {
  // WE DONT NEED THIS AS tmp_name HAS BEEN MOVED TO THE LOOP VARIABLE
  //  $tempFile = $_FILES['file']['tmp_name']; //3

  $targetPath = dirname(__file__) . $ds . $storeFolder . $ds; //4

  // IMPORTANT
  // WE USE THE $key WHICH IS THE INDEX INTO THE tmp_name ARRAY
  // TO FIND THE CORRESPONDING NAME IN THE name ARRAY

  $targetFile = $targetPath . $_FILES['file']['name'][$key]; //5

  move_uploaded_file($tempFile, $targetFile); //6

  // UPDATE DATABASE HERE
}

Open in new window

0
 

Author Comment

by:Eduardo Fuerte
Comment Utility
Thank you for your replies:

I'm going to carefully read it later - one by one.

This code runs the uploads:

    public function save()
    {
        try {


            $data = $this->input->post();


            $ds = DIRECTORY_SEPARATOR; //1

            
            //I'm going to change it.
            $storeFolder =  'C:/xampp/htdocs/meeta_ike/public/uploads/anexos/';

            

            if (!empty($_FILES)) {

               foreach ($_FILES as $key => $file) {
                    $i = 0;
                    foreach ($file['name'] as $name) {

                        $targetFile = $storeFolder.$name; //5
                        $tempFile = $file['tmp_name'][$i]; //3
                        
                        print_r($targetFile);
                        move_uploaded_file($tempFile, $targetFile);
                        $i++;
                    }


                }
            }

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
In my tests, DropZoneJS made one HTTP request for each file that was dropped into the zone.  It's not the same as a multi-file upload.  Therefore the appropriate way to handle the file upload(s) is expect to run the PHP action script once for each file.  That's what the example did, and it worked correctly, uploading one or more files, but each with its own HTTP request.  PHP $_POST was empty.  I did not check the request type or other variables -- it appears that all you need to use is the one "sub-array" in the $_FILES['file'] array (see the comments in the code example above).  I never even used foreach() because DropZone sent each request separately.  This is actually a good strategy - if one of the files is too big, or fails for some other reason, it does not impede the progress of the other files!

Like most PHP functions, move_uploaded_file() gives us the benefit of a return value.  You might want to check this and report any errors that occur.  The script I posted above will log an error if that happens.
0
 

Author Comment

by:Eduardo Fuerte
Comment Utility
The Codeigneter's controller still has a save() method to save all the form modal data to database, so $_FILES could be opened there and the files uploaded.

Since I'm using Codeigniter I couldn't use something like:
<form method="post" action="xxx.php" class="dropzone"">

Open in new window

Since it's breaked by Codeigniter's root.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
See lines 124/125 in my earlier example.  This worked for me.  It may be necessary to make some changes to CodeIgniter so that you can present the <form> tag in a way that allows the DropZone JavaScript to manipulate the form in the DOM.

$my_uploaded_file['name'] (see script above) is the only name you get from file upload processes.  Depending on where you store the file on your server, you may want to generate a more specific URL to store in the database.
0
 

Author Closing Comment

by:Eduardo Fuerte
Comment Utility
Thanks for help!
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
You are welcome.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This article discusses how to create an extensible mechanism for linked drop downs.
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now