Lolechi Lolechi - 1 year ago 131
PHP Question

Receiving file(s) via AJAX in server-side PHP

I'm sending (possibly) multiple user-input files via ajax to server-side PHP. I send it using a

object, and when I call
in the PHP it says the file object key inside
is an "unidentified index." I know I butchered the explanation, so here's context:


<form id="subForm" action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" multiple/>
<button type="submit">Post</button>


var files = $('input[type=file]').prop('files')[0]; //File list
var formData = new FormData();

//Cycle through files (if many)
for (var i = 0; i < files.length; i++) {
var file = files[i]; //File

//Type and size check
if (!file.type.match('image/*') && !file.type.match('video/*') && file.size > 8388608){

// Add the file to the request.
formData.append('files', file,;
type: 'POST',
url: 'submission.php', //Serverside handling script
enctype: 'multipart/form-data',
dataType: 'text', //Get back from PHP
processData: false, //Don't process the files
contentType: false,
cache: false,
data: formData,
success: function(php_script_response){


foreach($_FILES['files']['tmp_name'] as $key => $tmp_name){
if(is_uploaded_file($_FILES['files']['tmp_name'][$key]) && $_FILES['files']['tmp_name'][$key]['error']==0) {
$path = 'uploads/' . $_FILES['files']['name'][$key];
$upload = true;

$upload = false;

if(move_uploaded_file($_FILES['files']['name'][$key], $path)){
//File not uploaded/ saved?

Line 1 in the PHP returns:

Undefined index: files in C:\xampp\htdocs\submission.php

My speculation is that something is either wrong with my local apache server, or the JQuery?

Thanks in advance

Answer Source

The append is never reached because you are grabbing only a single value from the input with .prop('files')[0]. So, files.length is undefined in your loop. You should be grabbing the entire array of files:

var files = $('input[type=file]').prop('files'); //File list
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download