user9552143
user9552143

Reputation:

How to obtain chmod information via FTP

I am currently working on an online FTP client that would work similar to a normal FTP client found on a desktop. I am currently having trouble obtaining chmod permissions over FTP.

I have tried the fileperms() function in PHP, but it does not allow the FTP protocol, only intended to be used for local files on the server you are accessing.

Upvotes: 1

Views: 250

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202393

If you are using PHP 7.2 and newer and your FTP server supports MLSD command, it's easy, as you can use ftp_mlsd function.

$conn_id = ftp_connect("ftp.example.com") or die("Cannot connect");
ftp_login($conn_id, "username", "password") or die("Cannot login");
ftp_pasv($conn_id, true) or die("Cannot change to passive mode");
$entries = ftp_mlsd($conn_id, "/remote/path") or die("Cannot list directory");

foreach ($entries as $entry)
{
    if (($entry["type"] != "cdir") && ($entry["type"] != "pdir"))
    {
        echo $entry["name"] . " - " . $entry["UNIX.mode"] . "\n";
    }
}

If not, you have to use LIST command using ftp_rawlist function and parse a proprietary format that the server returns.

The following code assumes a common *nix format.

$entries = ftp_rawlist($conn_id, "/remote/path") or die("Cannot list directory");

foreach ($entries as $entry)
{
    $tokens = explode(" ", $entry);
    $name = $tokens[count($tokens) - 1];
    $permissions = $tokens[0];
    echo $name . " - " . $permissions . "\n";
}

Upvotes: 1

Related Questions