What are some best practices for handling file uploads and transfers in PHP using FTP functions?

When handling file uploads and transfers in PHP using FTP functions, it is important to ensure proper error handling, secure file permissions, and efficient file transfer methods. This can be achieved by checking for errors during the upload process, setting appropriate file permissions on the server, and using binary mode for transferring files to maintain file integrity.

// Connect to FTP server
$ftp_server = 'ftp.example.com';
$ftp_user = 'username';
$ftp_pass = 'password';
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user, $ftp_pass);

// Check connection
if ((!$conn_id) || (!$login_result)) {
    die('FTP connection failed!');
}

// Set passive mode
ftp_pasv($conn_id, true);

// Upload file
$local_file = 'local_file.txt';
$remote_file = 'remote_file.txt';
if (ftp_put($conn_id, $remote_file, $local_file, FTP_BINARY)) {
    echo "File uploaded successfully!";
} else {
    echo "Failed to upload file!";
}

// Close FTP connection
ftp_close($conn_id);