What are some best practices for handling FTP connections and directory creation in PHP?

When handling FTP connections and directory creation in PHP, it is important to establish a secure connection, handle errors gracefully, and properly set permissions for created directories. To achieve this, you can use PHP's built-in FTP functions and error handling mechanisms.

// Establish FTP connection
$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');
}

// Create directory
$dir = '/path/to/new/directory';
if (ftp_mkdir($conn_id, $dir)) {
    echo "Directory created successfully";
} else {
    echo "Failed to create directory";
}

// Close connection
ftp_close($conn_id);