Are there any best practices or recommended libraries for handling FTP uploads in PHP to avoid common pitfalls like connection failures?

When handling FTP uploads in PHP, it is important to use a reliable library such as PHP's built-in FTP functions or a third-party library like phpseclib. These libraries handle common pitfalls like connection failures by providing error handling mechanisms and retries for failed connections.

// Using PHP's built-in FTP functions
$ftp_server = "ftp.example.com";
$ftp_username = "username";
$ftp_password = "password";
$file_to_upload = "file.txt";

$ftp_conn = ftp_connect($ftp_server);
if (!$ftp_conn) {
    die("Failed to connect to FTP server");
}

$login = ftp_login($ftp_conn, $ftp_username, $ftp_password);
if (!$login) {
    die("Failed to login to FTP server");
}

$upload = ftp_put($ftp_conn, "remote/path/file.txt", $file_to_upload, FTP_ASCII);
if (!$upload) {
    die("Failed to upload file");
}

ftp_close($ftp_conn);