Refactor profile picture upload path handling and improve error logging

This commit is contained in:
Fabian Schieder 2026-01-25 22:41:19 +01:00
parent 392650e565
commit 26d665f2fe

View File

@ -60,25 +60,48 @@ if (!$mime || !isset($allowedMimeToExt[$mime]))
$ext = $allowedMimeToExt[$mime]; $ext = $allowedMimeToExt[$mime];
$targetDir = '/assets/images/profilePictures'; // Wichtig: Auf Linux ist ein Pfad mit führendem "/" ein Pfad ab Dateisystem-Root.
// Für move_uploaded_file() brauchen wir einen Dateisystempfad; die Public-URL ist separat.
$documentRoot = isset($_SERVER['DOCUMENT_ROOT']) ? (string)$_SERVER['DOCUMENT_ROOT'] : '';
$webRoot = rtrim($documentRoot, "\\/");
$targetDir = $webRoot !== ''
? $webRoot . '/assets/images/profilePictures'
: __DIR__ . '/assets/images/profilePictures';
if (!is_dir($targetDir)) if (!is_dir($targetDir))
{ {
@mkdir($targetDir, 0755, true); $mkOk = @mkdir($targetDir, 0755, true);
if (!$mkOk)
{
error_log('Upload: mkdir failed for ' . $targetDir);
header('Location: account.php?upload=err');
exit();
}
}
if (!is_writable($targetDir))
{
error_log('Upload: targetDir not writable: ' . $targetDir);
header('Location: account.php?upload=err');
exit();
} }
// Fallback-kompatibler Name (auch ohne random_bytes) // Fallback-kompatibler Name (auch ohne random_bytes)
$rand = uniqid('', true); $rand = uniqid('', true);
$rand = str_replace('.', '', $rand); $rand = str_replace('.', '', $rand);
$filename = 'user_' . $userId . '_' . $rand . '.' . $ext; $filename = 'user_' . $userId . '_' . $rand . '.' . $ext;
$targetPath = $targetDir . DIRECTORY_SEPARATOR . $filename; $targetPath = rtrim($targetDir, "\\/") . DIRECTORY_SEPARATOR . $filename;
if (!move_uploaded_file($tmp, $targetPath)) if (!move_uploaded_file($tmp, $targetPath))
{ {
$lastErr = error_get_last();
$lastErrMsg = (is_array($lastErr) && isset($lastErr['message'])) ? (string)$lastErr['message'] : 'unknown';
error_log('Upload: move_uploaded_file failed to ' . $targetPath . ' - ' . $lastErrMsg);
header('Location: account.php?upload=err'); header('Location: account.php?upload=err');
exit(); exit();
} }
// Pfad, der in HTML genutzt wird (relativ zur Webroot) // Pfad, der in HTML genutzt wird (URL relativ zur Webroot)
$publicPath = '/assets/images/profilePictures/' . $filename; $publicPath = '/assets/images/profilePictures/' . $filename;
$servername = "localhost"; $servername = "localhost";