Not getting the filename of a drag and drop image in PHP

I’m trying to create a form that has a drag and drop image with it. I did a tutorial for the drag and drop and now I’m trying to put it together with a form.

The problem I’m having is that I’m not able to get the filename, so that I can insert it into the database.

I’ve tried doing this

if(isset($_POST['add_product']))
{
    $filename = $_FILES['files']['name'];

    echo print_r($filename);
    die();
}

but I get a blank array

Array ( [0] => ) 1

and when I do this

if(isset($_FILES['files']))
{

    $filename = $_FILES['files']['name'];

    echo print_r($filename);
    die();

}

I get the name of my image, but if I do this

if(isset($_FILES['files']))
{
    $filename = $_FILES['files']['name'];
}

if(isset($_POST['add_product']))
{
    echo print_r($filename);
    die();
}

I get a blank array as well

Array ( [0] => ) 1

Here I was hoping that I could grab the $filename and pass it on to the

if(isset($_POST['add_product]))

Here is my form

<?php
    include "db.php";

    if(isset($_FILES['files']))
    {
        $filename = $_FILES['files']['name'];

    }

    if(isset($_POST['add_product']))
    {
        echo print_r($filename);
        die();
    }
?>

<form action="" method="POST" enctype="multipart/form-data">
    <div class="form-group">
        <label for="title">Title</label>
        <input type="text" class="form-control" name="title">
    </div>

    <div class="form-group">
        <label for="content">content</label>
        <textarea name="content" id="content" class="form-control" cols="30" rows="10"></textarea>
    </div>

    <input type="file" name="files[]" id="standard-upload-files" multiple>
    <input type="submit" value="Upload files" id="standard-upload">

    <div class="wrapper">
        <div class="upload-console">
            <h2 class="upload-console-header">
                Upload
            </h2>

            <div class="upload-console-body">
                <div class="upload-console-drop" id="drop-zone">
                    just drag and drop files here
                </div>

                <div class="bar">
                    <div class="bar-fill" id="bar-fill">
                        <div class="bar-fill-text" id="bar-fill-text"></div>
                    </div>
                </div>

                <div class="hidden" id="uploads-finished">
                    <h3>Process files</h3>

                    <div class="upload-console-upload">
                        <a href="#">filename.jpg</a>
                        <span>Success</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="form-group">
        <button type="submit" class="btn btn-dark btn-lg btn-block" name="add_product">Save</button>
    </div>
</form>

Here is the js files that I got from the tutorial that I did.

main.js

(function(){
    "use strict";

    var dropZone = document.getElementById('drop-zone');
    var barFill = document.getElementById('bar-fill');
    var barFillText = document.getElementById('bar-fill-text');
    var uploadsFinished = document.getElementById('uploads-finished');

    var startUpload = function(files){
        // console.log(files);
        app.uploader({
            files: files,
            progressBar: barFill,
            progressText: barFillText,
            processor: 'index.php',

            finished: function(data){
                // console.log(data);
                var x;
                var uploadedElement;
                var uploadedAnchor;
                var uploadedStatus;
                var currFile;

                for(x = 0; x < data.length; x = x + 1)
                {
                    currFile = data[x];

                    uploadedElement = document.createElement('div');
                    uploadedElement.className = 'upload-console-upload';

                    uploadedAnchor = document.createElement('a');
                    uploadedAnchor.textContent = currFile.name;

                    if(currFile.uploaded)
                    {
                        uploadedAnchor.href = 'uploads/'+currFile.file;
                    }

                    uploadedStatus = document.createElement('span');
                    uploadedStatus.textContent = currFile.uploaded ? 'Uploaded' : 'Failed';

                    uploadedElement.appendChild(uploadedAnchor);
                    uploadedElement.appendChild(uploadedStatus);

                    uploadsFinished.appendChild(uploadedElement);
                }

                uploadsFinished.className = '';

            },

            error: function(){
                console.log('there was an error');
            }
        });
    };

    //drop functionality

    dropZone.ondrop = function(e){
        e.preventDefault();
        this.className = 'upload-console-drop';

        startUpload(e.dataTransfer.files);
    };

    dropZone.ondragover = function(){
        this.className = 'upload-console-drop drop';
        return false;
    };

    dropZone.ondragleave = function(){
        this.className = 'upload-console-drop';
        return false;
    };
}());

upload.js

var app = app || {};

(function(o){
    "use strict";

    //private methods
    var ajax, getFormData, setProgress;

    ajax = function(data){


        var xmlhttp = new XMLHttpRequest();

        var uploaded;

        xmlhttp.addEventListener('readystatechange', function(){
            if(this.readyState === 4)
            {
                if(this.status === 200)
                {
                    uploaded = JSON.parse(this.response);

                    if(typeof o.options.finished === 'function')
                    {
                        o.options.finished(uploaded);
                    }
                }else{
                    if(typeof o.options.error === 'function')
                    {
                        o.options.error();
                    }
                }
            }
        });

        xmlhttp.upload.addEventListener('progress', function(e){
            var percent;

            if(e.lengthComputable === true)
            {
                percent = Math.round((event.loaded / event.total) * 100);
                setProgress(percent);
            }
        });

        xmlhttp.open('post', o.options.processor);
        xmlhttp.send(data);
    };

    getFormData = function(source){

        var data = new FormData();
        var i;

        for(i = 0; i < source.length; i = i + 1)
        {
            data.append('files[]', source[i]);
        }

        return data;
    };

    setProgress = function(value){
        if(o.options.progressBar !== undefined)
        {
            o.options.progressBar.style.width = value ? value + '%' : 0;
        }

        if(o.options.progressText !== undefined)
        {
            o.options.progressText.textContent = value ? value + '%' : '';
        }
    };

    o.uploader = function(options){

        o.options = options;

        if(options.files !== undefined)
        {
            ajax(getFormData(o.options.files));

            // getFormData(o.options.files);
        }
    }
}(app));

what do you get with

echo '<pre>' . print_r($_FILES, true) . '</pre>';

If I put

echo '<pre>' . print_r($_FILES, true) . '</pre>';

inside

if(isset($_FILES['files']))
{
    echo '<pre>' . print_r($_FILES, true) . '</pre>';
}

I get than array with nothing. It looks like this

Array
(
    [files] => Array
        (
            [name] => Array
                (
                    [0] => 
                )

            [type] => Array
                (
                    [0] => 
                )

            [tmp_name] => Array
                (
                    [0] => 
                )

            [error] => Array
                (
                    [0] => 4
                )

            [size] => Array
                (
                    [0] => 0
                )

        )

)

Array ( [0] => )

and if I put it in

if(isset($_POST['add_product']))
{
    echo '<pre>' . print_r($_FILES, true) . '</pre>';
}

Then I get the same empty array as above just twice

But that’s a definitive error message: https://www.php.net/manual/en/features.file-upload.errors.php

So you got a problem with your upload script.

This code is using ajax to upload the files, when they are drag and dropped. At the time the submit button is pressed, there’s nothing to upload (or perhaps the last/only file that was dropped.) If you want to see what the print_r($_FILES … data looks like for the actual upload, either log it to a file on the server or look at the network response in your browser’s developer tools.

If you are still having problems, it would be helpful if you posted the complete code of your page, so that we don’t have to piece it together and get it right/wrong compared with your actual code.

Sponsor our Newsletter | Privacy Policy | Terms of Service