What are some best practices for handling file uploads via SFTP in PHP?

When handling file uploads via SFTP in PHP, it is important to ensure the security and integrity of the uploaded files. One best practice is to validate the file type and size before accepting the upload. Additionally, use a secure connection to the SFTP server and handle any errors that may occur during the file transfer.

<?php

// Set up connection details
$server = 'sftp.example.com';
$username = 'username';
$password = 'password';
$port = 22;

// Connect to SFTP server
$connection = ssh2_connect($server, $port);
if (!$connection) {
    die('Connection failed');
}

// Authenticate with username and password
if (!ssh2_auth_password($connection, $username, $password)) {
    die('Authentication failed');
}

// Upload file to SFTP server
$localFile = 'localfile.txt';
$remoteFile = 'remotefile.txt';
if (ssh2_scp_send($connection, $localFile, $remoteFile)) {
    echo 'File uploaded successfully';
} else {
    echo 'File upload failed';
}

// Close the connection
ssh2_disconnect($connection);

?>