28

Is there a way to check if a a folder exists on the server using PHP Ftp functionality?

12 Answers 12

38

For PHP 5:

$folder_exists = is_dir('ftp://user:[email protected]/some/dir/path');

http://php.net/manual/en/function.is-dir.php : "As of PHP 5.0.0, this function can also be used with some URL wrappers."

http://php.net/manual/en/wrappers.ftp.php : [Support] "As of PHP 5.0.0: filesize(), filetype(), file_exists(), is_file(), and is_dir()"

6
  • Could this method use a pre-existing FTP buffer/login? If it could, what syntax should be used then? Let's say we have already done $ftp_buffer = ftp_connect($ftp_host); and ftp_login($ftp_buffer, $ftp_user, $ftp_pass);, then could we do something along is_dir('ftp:example.com/some/dir/path');? Commented Nov 19, 2014 at 4:39
  • 1
    @MajidFouladpour: No, this is completely different from the FTP extension, and it doesn't cooperate. php.net/manual/en/ref.ftp.php Commented Nov 19, 2014 at 12:08
  • @rob74: As they say, "you can't polish a turd". FTP is an ancient and outdated protocol; is it so surprising that anything built on top of it would be "far from awesome"? Commented Mar 2, 2016 at 15:25
  • 1
    @Piskvor: you're probably right - I was just frustrated because (a) ftp_mkdir doesn't have an easy way to check for the "dir already exists" return code (550 - I don't know if all servers use this value, but my code only needs to work with one server) and (b) there is no ftp_ function to check if a folder exists, so you have to use is_dir, which will probably open another connection. Maybe I'll try the ftp_nlist answer below, it seems at least a little bit less clumsy...
    – rob74
    Commented Mar 3, 2016 at 8:21
  • 1
    Useful tip: use clearstatcache() (if needed) so that is_dir()/is_file()/etc don't return cached results for multiple calls with the same URL. I was using the URL wrapper approach mentioned above for testing a simple FTP wrapper. is_dir() after mkdir() was true and after rmdir() was true too. cleartstatcache() resulted in the correct behaviour.
    – darrenp
    Commented Sep 25, 2016 at 18:25
18

Try this:

if (ftp_nlist($ftp_stream, $new_folder) == false) {
    ftp_mkdir($ftp_stream, $new_folder);
}
1
  • 4
    needs to be === then it works even if the folder is empty
    – dw1
    Commented Nov 24, 2018 at 14:21
7

There is no 'exists' function for ftp connections in php.

You could try ftp_chdir and check the result

1
  • this will dive you into folder you're checking, which is useless extra action, if you want just check if dir exists, so you'll have to go one level up with ftp_chdir again to get back
    – vladkras
    Commented Jan 16, 2017 at 11:04
5

stumbled upon this question from 2009 and found that question unsatisfying for me. I've done little research of my own a found a little tweak for that issue.

So if found the *ftp_nlist* function witch returns an array of string with files and folders names witch exist under the current ftp directory, and then I've simply checked under the array (with foreacah loop) if the folder or file we searched for exist there and an new ifExist method as been created.

you can read more at php.net: http://php.net/manual/en/function.ftp-nlist.php

another option for the YII framework users its the ftp extension that masks the php ftp lib and makes it even easier to work with an ftp server from code.

Hope you'l find helpful.

1
  • I wrote something similar, but using the 'in_array' function.
    – Tomás Cot
    Commented Apr 13, 2016 at 22:08
2

ftp_mdtm() gets the last modified time for a remote file. It returns the last modified time as a Unix timestamp on success, or -1 on error. Note that ftp_mdtm() does not work with directories. So if we get -1 then maybe the file is directory.

Note also that not all servers support this feature!

2

The solution that works for me:

if (!in_array($dirName.'/'.$something, $ftp->nlist($dirName))) {  
   // do something
}             
2

Me also not satisfied with any anwser incl. accepted one. I have standard connection (not O-O-style like in @Lackeeee's answer which is closest to mine):

$ftp = ftp_connect($host, 21, 30);
ftp_login($ftp, $user, $password);

// if $my_dir name exists in array returned by nlist in current '.' dir
if (in_array($my_dir, ftp_nlist($ftp, '.'))) {
    // do smth with $my_dir
}

ftp_close($ftp);
2

ftp_nlist already kinda does it:

function ftp_is_dir($path) {
  global $ftp_conn;
  $list = ftp_nlist($ftp_conn, $path);
  if ($list && count($list)>1) return true;
  else return false;
}

ftp_nlist returns an array of one element when a valid file (not folder) is given as $path, whereas, even an empty folder will yield 2 elements.

1
  • 1
    this misses a if ($path == '/') return true; after the global-line.
    – sjngm
    Commented Sep 9, 2021 at 10:46
1

for checking multiple files it is better to use ftp_chdir instead using the is_dir / file_exists function with URL wrappers, cause there are pretty slow (foreach file there must be opened a new ftp connection ...).

foreach ($list as $item) {
    $is_dir = @ftp_chdir($ftp_handle, $item); //produces warning if file...
    if ($is_dir) {
        ftp_chdir($ftp_handle, '..');
        $dirs[] = $item;
    } else {
        $files[] = $item;
    }
}

This script was ready after ~10 sec.

The same script using is_dir and file_exists needed more than 45 sec. (each file had 10 runs)

1

On modern FTP-servers you can use MLST/MLSD command to retrieve detailed machine-readable information about files. Read RFC page https://www.rfc-editor.org/rfc/rfc3659#page-23 to learn more about this command.

Here is sample code to determine filesystem node type:

function isDir($ftp, $fsNodePath) {
    $type = strtolower(fsNodeType($ftp, $fsNodePath));
    return ($type === 'cdir' || $type === 'pdir' || $type === 'dir');

}

function isFile($ftp, $fsNodePath) {
    $type = strtolower(fsNodeType($ftp, $fsNodePath));
    return ($type === 'file');
}

function isLink($ftp, $fsNodePath) {
    $type = strtolower(fsNodeType($ftp, $fsNodePath));
    return (preg_match('/^OS\.unix\=(slink|symlink)/i', $type) === 1);
}

function fsNodeType($ftp, $fsNodePath)
{
    $lines = array_values(ftp_raw($ftp, "MLST $fsNodePath"));
    $linesCount = count($lines);
    if ($linesCount === 1) {
        throw new Exception('Unsuitable response for MLST command: ' . $lines[0]);
    }
    if ($linesCount !== 3) {
        $e = new Exception('Unexpected response for MLST command (1)');
        $e->response = $lines;
        throw $e;
    }
    if (!preg_match('/^250\-/', $lines[0]) || !preg_match('/^250 /', $lines[2])) {
        $e = new Exception('Unexpected response for MLST command (2)');
        $e->response = $lines;
        throw $e;
    }
    $spEntry = ' ' . $lines[1];
    if (preg_match('/[\s\;]type\=([^\;]+)/i', $spEntry, $matches)) {
        $type = trim($matches[1]);
        return $type;
    } else {
        throw new Exception('Failed to extract filesystem node type from SP entry:' . $spEntry);
    }
}

$ftp = ftp_connect('192.168.0.100');
ftp_login($ftp, 'user', '1234');
$is = isDir($ftp, 'tmp');
var_dump($is);

Note that not every server supports MLST command. For example, ftp.freebsd.org does not :(

1

Here is a function to do this. It returns a simple true or false. It also handles some edge cases.

function isDir($connection, $dir)
{
    $dir = trim($dir, '/');
    $dir = '/' . $dir;
    if ($dir === '/') {
        return true;
    }
    return in_array($dir, ftp_nlist($connection, dirname($dir)));
}
0

You can create your own function:

function ftp_is_directory($ftp_conn, $dir)
{
    $pushd = ftp_pwd($ftp_conn);

    if ($pushd !== false && @ftp_chdir($ftp_conn, $dir))
    {
        ftp_chdir($ftp_conn, $pushd);   
        return true;
    }

    return false;
} 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.