What are some common pitfalls when using FTP in PHP to access external data sources?

One common pitfall when using FTP in PHP is not handling errors properly, which can lead to unexpected behavior or security vulnerabilities. To solve this, always check for errors after each FTP operation and handle them accordingly.

// Connect to FTP server
$ftp_server = 'ftp.example.com';
$ftp_user = 'username';
$ftp_pass = 'password';
$conn_id = ftp_connect($ftp_server);
if (!$conn_id) {
    die('Could not connect to FTP server');
}

// Login to FTP server
$login_result = ftp_login($conn_id, $ftp_user, $ftp_pass);
if (!$login_result) {
    die('FTP login failed');
}

// Perform FTP operations
// Example: Download a file
$file_path = '/path/to/file.txt';
$local_file = 'local_file.txt';
if (ftp_get($conn_id, $local_file, $file_path, FTP_BINARY)) {
    echo 'File downloaded successfully';
} else {
    echo 'Error downloading file';
}

// Close FTP connection
ftp_close($conn_id);