Skip to content Skip to sidebar Skip to footer

Why Is $_files[] Always Empty?

The problem I'm trying to make an AJAX file uploader with Php and Javascript. The problem I'm having is that in my upload.php script where I'm trying to use the move_uploaded_file

Solution 1:

According to the PHP docs, you must specify enctype="multipart/form-data". You must also specify method="post" -- see this answer for an explanation.

So your <form> should read:

<form class="form"id="upload_form" enctype="multipart/form-data" method="post">

Solution 2:

In one of my projects using Framework-7. I was doing the same to get file upload form submission using ajax.

Do what @kmoser suggest in his answer but do as below as well.:)

<form class="form"id="upload_form" enctype="multipart/form-data" method="post">
 <inputclass="button"type="submit"id="submission" value="Upload">

Now, my code:

$$('#submission').on('click', function(){
 //alert('here');//var test = $('#upload_form').serializeArray(); var fileInputElement = document.getElementById('file_to_upload');   

var formData = newFormData();  
formData.append('myfile', fileInputElement.files[0]);   
var request = newXMLHttpRequest();
request.open("POST", "https://yourwebsite/upload.php");
request.send(formData); 
    //console.log(request.response);

    request.onreadystatechange = function() {//Call a function when the state changes.if(request.readyState == 4 && request.status == 200) {
        alert("File has been uploaded successfully!");
        //console.log('here');
        location.reload();
    }
}
});

and at last on upload.php file write below code:

if(isset($_FILES['myfile'])) {       
    //echo "uploaded something";
    if($_FILES['myfile']['tmp_name'] != '') {
        $tmp_filenm = $_FILES['myfile']['tmp_name'];
        $file_name = time()."_".$_FILES['myfile']['name'];
        $file_fullpath = $today_dir."/".$file_name; 
        //echo $file_fullpath;
        move_uploaded_file("".$tmp_filenm,"$file_fullpath");

    }
}

Post a Comment for "Why Is $_files[] Always Empty?"