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

When handling file uploads via FTP in PHP, it is important to validate the file before uploading it, handle errors gracefully, and securely move the file to the desired location on the server. One best practice is to use the FTP functions provided by PHP to establish a connection, upload the file, and close the connection once the file has been transferred.

<?php

// FTP server credentials
$ftp_server = 'ftp.example.com';
$ftp_username = 'username';
$ftp_password = 'password';

// Local file to upload
$local_file = '/path/to/local/file.txt';

// Remote file path on the FTP server
$remote_file = '/path/on/server/file.txt';

// Connect to FTP server
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");

// Login to FTP server
$login = ftp_login($ftp_conn, $ftp_username, $ftp_password);

// Upload file
if (ftp_put($ftp_conn, $remote_file, $local_file, FTP_BINARY)) {
    echo "File uploaded successfully";
} else {
    echo "Failed to upload file";
}

// Close FTP connection
ftp_close($ftp_conn);

?>