What are common pitfalls when using PHP to upload files via FTP and how can they be avoided?

Common pitfalls when using PHP to upload files via FTP include not properly handling errors, not sanitizing user input, and not setting the correct permissions on the uploaded files. To avoid these issues, make sure to check for errors after each FTP operation, validate and sanitize user input before uploading files, and set appropriate permissions on the uploaded files.

// Example code snippet to upload a file via FTP in PHP with error handling, input validation, and setting correct permissions

$ftp_server = "ftp.example.com";
$ftp_username = "username";
$ftp_password = "password";
$file_to_upload = "file.txt";

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

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

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

// Upload file
if (ftp_put($conn_id, $file_to_upload, $file_to_upload, FTP_ASCII)) {
    echo "File uploaded successfully";
} else {
    echo "Failed to upload file";
}

// Close FTP connection
ftp_close($conn_id);