<?php
/**
* SFTPnewfile.php
* Creates an empty file on the remote SFTP server
*/
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
ob_start(); // buffer output to prevent accidental spaces
session_start();
$response = ['success' => false, 'message' => ''];
// Validate session
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
$response['message'] = 'POST only';
clean_exit($response);
}
if (empty($_SESSION['sftp_connected']) || empty($_SESSION['sftp_config'])) {
$response['message'] = 'Not connected to SFTP';
clean_exit($response);
}
require_once __DIR__ . '/SFTPconnector.php';
$config = $_SESSION['sftp_config'];
$input = json_decode(file_get_contents('php://input'), true);
$path = $input['path'] ?? '';
if (!$path) {
$response['message'] = 'No file path provided';
clean_exit($response);
}
// Connect using stored session config
$connector = extension_loaded('ssh2') ? new SFTPConnector() : new SystemSFTPConnector();
$result = $connector->connect($config['host'], (int)$config['port'], $config['username'], $config['password']);
if ($result !== true) {
$response['message'] = 'Reconnection failed: ' . $result;
clean_exit($response);
}
// Create empty temp file
$tmp = tempnam(sys_get_temp_dir(), 'sftp_');
file_put_contents($tmp, ""); // blank file
$upload = $connector->uploadFile($tmp, $path);
unlink($tmp);
if ($upload === true) {
$response['success'] = true;
$response['message'] = 'Blank file created successfully';
} else {
$response['message'] = 'Failed: ' . $upload;
}
clean_exit($response);
// --- Helper: safely output JSON and end ---
function clean_exit(array $response): void {
// Clear any previous buffered output (whitespace, PHP warnings, etc.)
if (ob_get_length()) ob_clean();
echo json_encode($response, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
exit;
}