What are some best practices for transferring files to an FTP server using PHP?

Transferring files to an FTP server using PHP requires establishing a connection to the server, logging in with valid credentials, and then using FTP functions to upload the files. It is important to handle errors and exceptions during the transfer process to ensure the files are successfully uploaded.

// Set up FTP connection
$ftp_server = 'ftp.example.com';
$ftp_user = 'username';
$ftp_pass = 'password';
$ftp_conn = ftp_connect($ftp_server);

// Login to FTP server
if (ftp_login($ftp_conn, $ftp_user, $ftp_pass)) {
    // Upload file to FTP server
    $local_file = 'local_file.txt';
    $remote_file = 'remote_file.txt';
    if (ftp_put($ftp_conn, $remote_file, $local_file, FTP_ASCII)) {
        echo 'File uploaded successfully';
    } else {
        echo 'Failed to upload file';
    }
} else {
    echo 'Failed to connect to FTP server';
}

// Close FTP connection
ftp_close($ftp_conn);