<?php
// SFTPdownload.php - Download file content from SFTP
header('Content-Type: text/plain; charset=utf-8');
ob_start();
session_start();
try {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
throw new Exception('POST requests only');
}
if (empty($_SESSION['sftp_connected']) || empty($_SESSION['sftp_config'])) {
throw new Exception('Not connected to SFTP server');
}
require_once __DIR__ . '/SFTPconnector.php';
$config = $_SESSION['sftp_config'];
$input = json_decode(file_get_contents('php://input'), true);
$remotePath = $input['path'] ?? '';
if (!$remotePath) {
throw new Exception('Missing file path');
}
// Connect to SFTP
if (extension_loaded('ssh2')) {
$connector = new SFTPConnector();
} else if (function_exists('exec')) {
$connector = new SystemSFTPConnector();
} else {
throw new Exception('No SFTP method available');
}
$connectResult = $connector->connect(
$config['host'],
(int)$config['port'],
$config['username'],
$config['password']
);
if ($connectResult !== true) {
throw new Exception("Connection failed: $connectResult");
}
// Download file to temp location
$tempFile = tempnam(sys_get_temp_dir(), 'sftp_download_');
$result = $connector->downloadFile($remotePath, $tempFile);
if ($result !== true) {
if (file_exists($tempFile)) unlink($tempFile);
throw new Exception("Download failed: $result");
}
// Read and return content
if (!file_exists($tempFile)) {
throw new Exception('Downloaded file not found');
}
$content = file_get_contents($tempFile);
unlink($tempFile);
if ($content === false) {
throw new Exception('Failed to read file content');
}
// Update last activity
$_SESSION['sftp_last_activity'] = time();
// Clear output buffer and return content
if (ob_get_length()) ob_clean();
echo $content;
} catch (Throwable $e) {
if (ob_get_length()) ob_clean();
http_response_code(400);
echo 'Error: ' . $e->getMessage();
}
?>