ftp_close() function in PHP

The ftp_close() function in PHP is used to close an active FTP connection that was previously established using ftp_connect(). This function helps free up system resources and properly terminates the connection.

Syntax

ftp_close($connection);

Parameters

  • $connection − The FTP connection resource to close, returned by ftp_connect().

Return Value

The ftp_close() function returns TRUE on success or FALSE on failure.

Example

The following example demonstrates connecting to an FTP server, performing directory operations, and properly closing the connection −

<?php
    $ftp_server = "ftp.example.com";
    $ftp_user = "kevin";
    $ftp_pass = "tywg61gh";
    
    // Establish FTP connection
    $connection = ftp_connect($ftp_server);
    $login_result = ftp_login($connection, $ftp_user, $ftp_pass);
    
    if ($login_result) {
        // Change to demo directory
        ftp_chdir($connection, 'demo');
        echo "Current directory: " . ftp_pwd($connection) . "<br>";
        
        // Move up one directory
        if (ftp_cdup($connection)) {
            echo "Directory changed successfully!<br>";
        } else {
            echo "Directory change failed!<br>";
        }
        
        echo "New directory: " . ftp_pwd($connection) . "<br>";
        
        // Close the FTP connection
        if (ftp_close($connection)) {
            echo "FTP connection closed successfully.<br>";
        }
    } else {
        echo "FTP login failed!<br>";
    }
?>

Key Points

  • Always close FTP connections when finished to free system resources

  • The function returns TRUE if the connection is closed successfully

  • It's good practice to check if operations succeed before closing the connection

  • Once closed, the connection resource becomes invalid and cannot be reused

Conclusion

The ftp_close() function is essential for properly terminating FTP connections and freeing up resources. Always use it after completing FTP operations to maintain good programming practices.

Updated on: 2026-03-15T07:39:10+05:30

180 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements