The problem is that everything seems to function except when I actually try to upload a file and click on the submit button, I think the file gets processed but the php doesn't handle it for some reason (I don't really know much about php, this was taken from an online tutorial so I'm not sure where I'm going wrong). The array of files isn't being sent to the php file.
The HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Upload Files</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload File" name="submit">
</form>
<script src="upload.js"></script>
</body>
</html>
The JavaScript code:
const url = 'process.php';
const form = document.querySelector('form');
form.addEventListener('submit', e => {
e.preventDefault();
const files = document.querySelector('[type=file]').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('files[]', file);
}
fetch(url, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
});
});
The php code:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_FILES['files'])) {
$errors = [];
$path = 'uploads/';
$extensions = ['m4a', 'mp3', 'mkv', 'mp4', 'wav', 'flac', 'alac', 'aiff', 'avi'];
$all_files = count($_FILES['files']['tmp_name']);
print_r('hi');
for ($i = 0; $i < $all_files; $i++) {
$file_name = $_FILES['files']['name'][$i];
$file_tmp = $_FILES['files']['tmp_name'][$i];
$file_type = $_FILES['files']['type'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_ext = strtolower(end(explode('.', $_FILES['files']['name'][$i])));
$file = $path . $file_name;
if (!in_array($file_ext, $extensions)) {
$errors[] = 'Extension not allowed: ' . $file_name . ' ' . $file_type;
}
if ($file_size > 50000000) {
$errors[] = 'File size exceeds limit: ' . $file_name . ' ' . $file_type;
}
if (empty($errors)) {
move_uploaded_file($file_tmp, $file);
}
}
if ($errors) print_r($errors);
}
}
In the php code, if I try a print statement within the "if (isset($_FILES['files']))" loop, it never prints out anything, so that loop is never entered, meaning the files did not go through, even though if I try to console log the files array in my Javascript code, it shows up correctly in my Developer Tools.