Ik heb een probleem met mijn script dat JSON data verwerkt en ik kom er niet helemaal uit wat er misgaat. Ik hoop dat iemand hier mij kan helpen.
Alvast bedankt voor jullie hulp!

<?php
session_start();
if (!defined('********')) {
define('********', true);
}
error_reporting(E_ALL);
ini_set('display_errors', 1);
include_once("********.php");
if(empty($picture_upload_style)){
echo "<link rel=\"stylesheet\" href=\"https://www.********.nl/style.css\"> <!-- css version 1e -->";
}
function encryptFile($source, $dest, $key) {
if (is_null($key)) {
throw new Exception('Encryption key is not set');
}
$key = substr(hash('sha256', $key, true), 0, 32);
$iv = openssl_random_pseudo_bytes(16);
$input = file_get_contents($source);
$ciphertext = openssl_encrypt($input, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
file_put_contents($dest, $iv . $ciphertext);
}
function json_response($success, $data = null, $error = null) {
$response = ['success' => $success];
if ($data !== null) {
$response['data'] = $data;
}
if ($error !== null) {
$response['error'] = $error;
}
echo json_encode($response);
exit;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['image'])) {
header('Content-Type: application/json');
ob_start(); // Start output buffering
try {
if (!isset($_SESSION['email'], $_SESSION['session_id'])) {
throw new Exception('Session not set');
}
$email = $_SESSION['email'];
$session_id = $_SESSION['session_id'];
$stmt = $dbcreat->prepare("SELECT * FROM members WHERE md5(email) = ? AND session_id = ?");
if ($stmt === false) {
throw new Exception("Connection error: " . $dbcreat->error);
}
$stmt->bind_param("ss", $email, $session_id);
$stmt->execute();
$result = $stmt->get_result();
if (!$data = $result->fetch_assoc()) {
session_destroy();
throw new Exception('User not authenticated');
}
$userId = $data['id'];
$uploadDir = 'user_upload/' . $userId . '/';
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0775, true);
}
$uploadedFiles = [];
foreach ($_FILES['image']['name'] as $index => $name) {
if ($_FILES['image']['error'][$index] != UPLOAD_ERR_OK) {
throw new Exception('File upload error: ' . $_FILES['image']['error'][$index]);
}
$fileExtension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
$fileSize = $_FILES['image']['size'][$index];
$allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
$maxFileSize = 5 * 1024 * 1024; // 5MB
if (!in_array($fileExtension, $allowed_extensions)) {
throw new Exception('Invalid file type');
}
if ($fileSize > $maxFileSize) {
throw new Exception('File size exceeds limit');
}
$tmpFilePath = $_FILES['image']['tmp_name'][$index];
$randomNumber = mt_rand(100000, 999999);
while (file_exists($uploadDir . $randomNumber . '.' . $fileExtension)) {
$randomNumber = mt_rand(100000, 999999);
}
$filePath = $uploadDir . $randomNumber . '.' . $fileExtension;
if (!$encryption_key) {
throw new Exception('Encryption key not found');
}
encryptFile($tmpFilePath, $filePath, $encryption_key);
$stmt = $dbcreat->prepare("INSERT INTO images (userid, image_link, password, password_lock) VALUES (?, ?, ?, ?)");
if (!$stmt) {
throw new Exception('SQL prepare failed: ' . $dbcreat->error);
}
$password = null;
$password_lock = 0;
if (isset($_POST['password']) && !empty($_POST['password'])) {
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$password_lock = 1;
}
$stmt->bind_param('issi', $userId, $filePath, $password, $password_lock);
if (!$stmt->execute()) {
throw new Exception($stmt->error);
}
$stmt->close();
$uploadedFiles[] = $filePath;
}
ob_clean(); // Clear the buffer before sending JSON response
json_response(true, ['files' => $uploadedFiles]);
} catch (Exception $e) {
ob_clean(); // Clear the buffer in case of an error
json_response(false, null, $e->getMessage());
}
} else {
// Display upload form and gallery
echo '<div class="content-box">
<div id="drop-area">
<form class="my-form" enctype="multipart/form-data">
<p>Upload multiple files with the file dialog or by dragging and dropping images onto the dashed region</p>
<input type="file" id="fileElem" name="image[]" multiple accept="image/*" onchange="handleFiles(this.files)">
<input type="password" id="filePassword" name="password" placeholder="Optional: Set a password for images">
<label class="button" for="fileElem">Select some files</label>
</form>
<progress id="progress-bar" max="100" value="0"></progress>
<div id="gallery"></div>
</div>';
// Display uploaded images
$userId = $data['id'] ?? 0; // Replace with appropriate session user ID
if ($userId) {
$stmt = $dbcreat->prepare("SELECT image_link FROM images WHERE userid = ?");
$stmt->bind_param('i', $userId);
$stmt->execute();
$result = $stmt->get_result();
echo '<div class="uploaded-images">';
while ($row = $result->fetch_assoc()) {
echo '<a href="' . $row['image_link'] . '" target="_blank">' . basename($row['image_link']) . '</a><br>';
}
echo '</div>';
}
echo '</div>';
}
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
let dropArea = document.getElementById('drop-area');
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, preventDefaults, false);
document.body.addEventListener(eventName, preventDefaults, false);
});
['dragenter', 'dragover'].forEach(eventName => {
dropArea.addEventListener(eventName, highlight, false);
});
['dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, unhighlight, false);
});
dropArea.addEventListener('drop', handleDrop, false);
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
function highlight(e) {
dropArea.classList.add('highlight');
}
function unhighlight(e) {
dropArea.classList.remove('highlight');
}
function handleDrop(e) {
let dt = e.dataTransfer;
let files = dt.files;
handleFiles(files);
}
function handleFiles(files) {
([...files]).forEach(uploadFile);
}
function uploadFile(file) {
let formData = new FormData();
formData.append('image[]', file);
let password = document.getElementById('filePassword').value;
if (password) {
formData.append('password', password);
}
fetch('', {
method: 'POST',
body: formData
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log('Upload result:', data);
if (data.success) {
alert("Upload successful!");
displayUploadedFiles(data.data.files);
} else {
alert("Upload failed: " + data.error);
}
})
.catch(error => {
console.error('Upload error:', error);
alert("Upload error: " + error.message);
});
}
function displayUploadedFiles(files) {
let gallery = document.getElementById('gallery');
files.forEach(file => {
let link = document.createElement('a');
link.href = file;
link.target = '_blank';
link.textContent = file;
gallery.appendChild(link);
gallery.appendChild(document.createElement('br'));
});
}
});
</script>