Question

I am using the following code to upload files without refreshing my page but I need to send the userid of the currently logged in user together with the files, which is stored in $_SESSION['UserID'].

var fileSelect = document.getElementById('file');
var files = fileSelect.files;
var formData = new FormData();
var div = document.getElementById('UploadInfo');

// Loop through each of the selected files.
for (var i = 0; i < files.length; i++) {
    var file = files[i];

    // Check the file type.
    if (!file.type.match('image.*')) {
        alert("File: " + file.name + " is not an image and will not be uploaded.");
        continue;
    }

    // Add the file to the request.
    formData.append('images[]', file, file.name);
}

var xhr = new XMLHttpRequest();
xhr.open('POST', 'Php/upload_file.php', true);
xhr.send(formData);

I have tried using the following line without success, which means i am not recieveing the userid value in my phpscript, $_POST is empty and $_FILES contains only the fileinfo.

formData.append('UserID', '<%=$_SESSION["UserID"] %>');

Is there any other way I can accomplish this?

My PHP code:

if(isset($_FILES)) {
$numberOfFiles = count($_FILES['images']['name']);
for($id = 0; $id < $numberOfFiles; $id++)
{
    if (file_exists($_FILES["images"]["tmp_name"][$id])) {
        $destination = "../UploadedImages/" . $_FILES['UserID'] . $_FILES["images"]["name"][$id];
        move_uploaded_file($_FILES["images"]["tmp_name"][$id], $destination);
    }
}

}

exit();

Was it helpful?

Solution

It looks like you need to use $_POST in your php script, you had $_FILES['UserID'] instead of $_POST['UserID'] .I also added a check to see if the UserID was passed, and added a variable $userId, then if $_POST['UserID'] did not get passed to the php script, i use die and send back an error.

NOTE: You should be checking $_POST['UserID'] to make sure it doesn't contain SQL injection scripts, or harmful code that can cause issues.

if(isset($_FILES) || isset($_POST)) {

    $numberOfFiles = count($_FILES['images']['name']);
    $userId = ''; //Create userId variable

    //Check if the UserID exists in the autoglobal $_POST
    if(array_key_exists('UserID', $_POST) === true) { 
        //Now we can add UserId to our variable
        $userId = $_POST['UserID']; 

    } else { 

        die('UserID was not passed');

    }

    for($id = 0; $id < $numberOfFiles; $id++)
    {
        if (file_exists($_FILES["images"]["tmp_name"][$id])) {
            $destination = $userId . $_FILES["images"]["name"][$id];
            move_uploaded_file($_FILES["images"]["tmp_name"][$id], $destination);
        }
    }


} else {
   echo "$_POST and $_FILES dont exist";
}

Edits: Fixed up some syntax errors, please re look at the code and make sure you have the latest version.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top