79 lines
2.3 KiB
PHP
79 lines
2.3 KiB
PHP
<?php
|
|
session_set_cookie_params([
|
|
'lifetime' => 0,
|
|
'path' => '/',
|
|
'domain' => '',
|
|
'secure' => false,
|
|
'httponly' => true,
|
|
'samesite' => 'Lax'
|
|
]);
|
|
session_start();
|
|
|
|
header('Content-Type: application/json');
|
|
error_reporting(E_ALL);
|
|
ini_set('display_errors', '0');
|
|
|
|
if (empty($_SESSION['user_logged_in'])) {
|
|
http_response_code(401);
|
|
echo json_encode(['error' => 'Nicht eingeloggt']);
|
|
exit;
|
|
}
|
|
|
|
include_once(__DIR__ . '/../../../controller/DatabaseController.php');
|
|
|
|
$UPLOAD_DIR = __DIR__ . '/../../../uploads/';
|
|
$MAX_GROESSE = 20 * 1024 * 1024; // 20 MB
|
|
$VERBOTENE_ENDUNGEN = ['php', 'phtml', 'php3', 'php4', 'php5', 'phar', 'exe', 'sh', 'bat', 'cgi', 'htaccess'];
|
|
|
|
try {
|
|
if (empty($_FILES['datei'])) {
|
|
throw new InvalidArgumentException('Keine Datei übermittelt');
|
|
}
|
|
|
|
$datei = $_FILES['datei'];
|
|
|
|
if ($datei['error'] !== UPLOAD_ERR_OK) {
|
|
throw new InvalidArgumentException('Fehler beim Upload (Code ' . $datei['error'] . ')');
|
|
}
|
|
|
|
if ($datei['size'] > $MAX_GROESSE) {
|
|
throw new InvalidArgumentException('Datei zu groß (max. 20 MB)');
|
|
}
|
|
|
|
$originalName = basename($datei['name']); // gegen Path Traversal im Namen
|
|
$endung = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
|
|
|
|
if (in_array($endung, $VERBOTENE_ENDUNGEN, true)) {
|
|
throw new InvalidArgumentException('Dieser Dateityp ist nicht erlaubt');
|
|
}
|
|
|
|
// Zufälliger, kollisionssicherer Speichername - Original bleibt nur in der DB erhalten
|
|
$speicherName = bin2hex(random_bytes(16)) . ($endung !== '' ? '.' . $endung : '');
|
|
$zielPfad = $UPLOAD_DIR . $speicherName;
|
|
|
|
if (!move_uploaded_file($datei['tmp_name'], $zielPfad)) {
|
|
throw new Exception('Datei konnte nicht gespeichert werden');
|
|
}
|
|
|
|
$mimeType = mime_content_type($zielPfad) ?: 'application/octet-stream';
|
|
|
|
DatabaseInsert(
|
|
"Dateien",
|
|
"ORIGINALNAME, SPEICHERNAME, GROESSE, MIME_TYPE, HOCHGELADEN_VON",
|
|
$originalName,
|
|
$speicherName,
|
|
$datei['size'],
|
|
$mimeType,
|
|
$_SESSION['username']
|
|
);
|
|
|
|
echo json_encode(['success' => true]);
|
|
|
|
} catch (InvalidArgumentException $e) {
|
|
http_response_code(400);
|
|
echo json_encode(['error' => $e->getMessage()]);
|
|
} catch (Throwable $e) {
|
|
http_response_code(500);
|
|
error_log($e->getMessage());
|
|
echo json_encode(['error' => 'Serverfehler']);
|
|
} |