ftp_nlist() function in PHP

The ftp_nlist() function returns a list of files in the specified directory on the FTP server. It provides a simple way to retrieve file names without detailed information like file sizes or permissions.

Syntax

ftp_nlist(con, dir);

Parameters

  • con − The FTP connection resource created by ftp_connect()

  • dir − The directory path to be listed. Use "." for current directory

Return Value

The ftp_nlist() function returns an array of file names on success or FALSE on failure.

Example

The following example demonstrates how to get the list of files in the current directory ?

<?php
    $ftp_server = "192.168.0.4";
    $ftp_user = "tim";
    $ftp_pass = "wthbn#@121";
    
    // Connect to FTP server
    $con = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
    $login = ftp_login($con, $ftp_user, $ftp_pass);
    
    // Get file list from current directory
    $list = ftp_nlist($con, ".");
    
    if ($list !== false) {
        echo "Files in current directory:<br>";
        foreach ($list as $file) {
            echo $file . "<br>";
        }
    } else {
        echo "Failed to retrieve file list";
    }
    
    // Close connection
    ftp_close($con);
?>
Files in current directory:
document.txt
image.jpg
script.php
data.csv

Listing Specific Directory

You can also list files from a specific directory path ?

<?php
    $con = ftp_connect("192.168.0.4");
    ftp_login($con, "username", "password");
    
    // List files in uploads directory
    $files = ftp_nlist($con, "/uploads");
    
    if ($files) {
        print_r($files);
    }
    
    ftp_close($con);
?>

Conclusion

The ftp_nlist() function provides a simple way to retrieve file names from FTP directories. Always check the return value for FALSE to handle connection errors gracefully.

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

143 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements