<?php
session_start();
header('Content-Type: application/json');
// Config
$host = 'your.sftp.host';
$port = 22;
$user = 'your_username';
$pass = 'your_password';
$remoteDir = '/path/on/remote/server/';
$action = $_GET['action'] ?? null;
// Connect SFTP
$conn = @ssh2_connect($host, $port);
if (!$conn || !@ssh2_auth_password($conn, $user, $pass)) {
echo json_encode(['error' => 'Failed to connect to SFTP']);
exit;
}
$sftp = ssh2_sftp($conn);
// --- List files ---
if ($action === 'list') {
$handle = opendir("ssh2.sftp://$sftp$remoteDir");
$files = [];
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') continue;
$files[] = $file;
}
echo json_encode(['files' => $files]);
exit;
}
// --- Upload files ---
if ($action === 'upload') {
if (empty($_FILES['files'])) {
echo json_encode(['error' => 'No files provided']);
exit;
}
$uploaded = [];
foreach ($_FILES['files']['tmp_name'] as $i => $tmp) {
$name = basename($_FILES['files']['name'][$i]);
$remotePath = "ssh2.sftp://$sftp$remoteDir$name";
if (copy($tmp, $remotePath)) $uploaded[] = $name;
}
echo json_encode(['message' => 'Uploaded successfully', 'files' => $uploaded]);
exit;
}
echo json_encode(['error' => 'Unknown action']);