How to connect to SFTP using PHP8.3.

To ensure the connection is SFTP, we need to use PHP’s SSH2 extension instead of the FTP functions. The ssh2_sftp extension allows secure file transfers over SFTP.

Updated SFTP Upload Function

This version connects to an SFTP server on port 22, uploads an XML file to the /data directory, and closes the connection when done.

<?php
function uploadXmlFileSFTP(string $localFilePath, string $remoteFileName): bool {
    // SFTP server details
    $sftpServer = "your-sftp-server.com";
    $sftpPort = 21222; // Custom SFTP port
    $sftpUsername = "your-username";
    $sftpPassword = "your-password";
    $remoteDirectory = "/data"; // Target directory on the remote server

    // Ensure the file exists before proceeding
    if (!file_exists($localFilePath)) {
        error_log("Error: File not found - $localFilePath");
        return false;
    }

    // Establish SSH connection
    $connection = ssh2_connect($sftpServer, $sftpPort);
    if (!$connection) {
        error_log("Error: Could not connect to SFTP server $sftpServer on port $sftpPort");
        return false;
    }

    // Authenticate with username and password
    if (!ssh2_auth_password($connection, $sftpUsername, $sftpPassword)) {
        error_log("Error: SFTP authentication failed");
        return false;
    }

    // Initialize SFTP subsystem
    $sftp = ssh2_sftp($connection);
    if (!$sftp) {
        error_log("Error: Could not initialize SFTP subsystem");
        return false;
    }

    // Define the remote file path
    $remoteFilePath = "ssh2.sftp://$sftp$remoteDirectory/$remoteFileName";

    // Upload the XML file
    if (!copy($localFilePath, $remoteFilePath)) {
        error_log("Error: Failed to upload $localFilePath to $remoteFilePath");
        return false;
    }

    return true; // SFTP connection automatically closes when the script ends
}

// Example usage
$localFile = "path/to/your/file.xml";
$remoteFile = "file.xml"; // Name to save on the remote server

if (uploadXmlFileSFTP($localFile, $remoteFile)) {
    echo "Upload successful!";
} else {
    echo "Upload failed.";
}
?>

Requirements:

Make sure the SSH2 extension is installed in PHP (php-ssh2). You can check with:

php -m | grep ssh2

If not installed, add it via:

sudo apt install php-ssh2 # Ubuntu/Debian
brew install php-ssh2     # macOS (Homebrew)

You might also want to try installing for a particular version of PHP if you’re running more than one.

sudo apt install php8.3-ssh2 # Ubuntu/Debian

Once it’s installed you should be able to use the ssh2_ functions.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *