is_dir($directoryPath) && !$sftp->mkdir($directoryPath, 0755, true)) { http_response_code(500); exit('Failed to create upload directory.'); } } } $uploadedFiles = $_FILES['files'] ?? null; if (!$uploadedFiles || empty($uploadedFiles['name'][0])) { http_response_code(400); exit('No files received or file size exceeds PHP limits.'); } $uploadErrors = [ UPLOAD_ERR_INI_SIZE => 'File exceeds upload_max_filesize directive in php.ini', UPLOAD_ERR_FORM_SIZE => 'File exceeds MAX_FILE_SIZE directive in the HTML form', UPLOAD_ERR_PARTIAL => 'File was only partially uploaded', UPLOAD_ERR_NO_FILE => 'No file was uploaded', UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder', UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk', UPLOAD_ERR_EXTENSION => 'A PHP extension stopped the file upload', ]; $uploadMessages = []; $anySuccess = false; $failureStatus = 500; foreach ($uploadedFiles['tmp_name'] as $index => $temporaryPath) { $fileName = $uploadedFiles['name'][$index]; $relativePath = $_POST['paths'][$index] ?? ''; $uploadError = $uploadedFiles['error'][$index]; if ($uploadError !== UPLOAD_ERR_OK) { $failureStatus = 400; $uploadMessages[] = $fileName . ': ' . ($uploadErrors[$uploadError] ?? 'Unknown upload error'); continue; } $remotePath = requireRemotePath(rtrim($currentPath, '/') . '/' . ($relativePath !== '' ? $relativePath : $fileName), $currentPath); if ($remotePath === $currentPath) { http_response_code(400); exit('Invalid upload path.'); } $directoryPath = remoteDirname($remotePath); if (!$sftp->is_dir($directoryPath) && !$sftp->mkdir($directoryPath, 0755, true)) { $uploadMessages[] = 'Failed to create directory for: ' . $fileName; continue; } if ($sftp->put($remotePath, $temporaryPath, SFTP::SOURCE_LOCAL_FILE)) { $uploadMessages[] = 'Uploaded: ' . ($relativePath !== '' ? $relativePath : $fileName); $anySuccess = true; } else { $uploadMessages[] = 'Failed to upload: ' . ($relativePath !== '' ? $relativePath : $fileName); } } if (!$anySuccess) { http_response_code($failureStatus); } header('Content-Type: text/plain; charset=UTF-8'); echo implode("\n", $uploadMessages);