<?php
header('Content-Type: application/json');
session_start();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['success' => false, 'message' => 'POST only']);
exit;
}
if (!isset($_SESSION['sftp_connected'], $_SESSION['sftp_config'])) {
echo json_encode(['success' => false, 'message' => 'Not connected to SFTP']);
exit;
}
if (!isset($_FILES['file'])) {
echo json_encode(['success' => false, 'message' => 'No file uploaded']);
exit;
}
require_once 'SFTPconnector.php';
$config = $_SESSION['sftp_config'];
$connector = extension_loaded('ssh2') ? new SFTPConnector() : new SystemSFTPConnector();
$result = $connector->connect($config['host'], $config['port'], $config['username'], $config['password']);
if ($result !== true) {
echo json_encode(['success' => false, 'message' => 'Reconnection failed: '.$result]);
exit;
}
$tmp = $_FILES['file']['tmp_name'];
$remotePath = rtrim($_POST['path'] ?? '/', '/') . '/' . basename($_FILES['file']['name']);
$upload = $connector->uploadFile($tmp, $remotePath);
if ($upload === true) {
echo json_encode(['success' => true, 'message' => 'File uploaded successfully']);
} else {
echo json_encode(['success' => false, 'message' => 'Upload failed: '.$upload]);
}
?>