4

I have the following function in my model:

public function createfolder($location, $name){
    define('NET_SFTP_LOGGING', NET_SFTP_LOG_COMPLEX);
    $sftp = new Net_SFTP('xx.xxx.xx.xx');
    if (!$sftp->login('admin', '********')) {
        exit('Login Failed');
    }
    //moves to a location (Job folder for example)
    $sftp->chdir($location);
    //makes the folder
    $sftp->mkdir($name);
}

This will work but I would like to add some sort of error prevention validation, how can I check if a folder exists using SFTP?


Think I came up with a solution:

chdir() changes directories, mkdir() creates directories, and rmdir() removes directories. In the event of failure, they all return false. chdir(), mkdir(), and rmdir() return true on successful completion of the operation.

So I can use an if statement to check if chdir() === true or false to see if the directory is there.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Someone
  • 894
  • 3
  • 22
  • 43

2 Answers2

5

You can use $sftp->is_dir($location) to check if it's a directory.

Frits
  • 7,341
  • 10
  • 42
  • 60
ownking
  • 1,956
  • 1
  • 24
  • 34
1

I think your solution is a good one.

In theory you could also do something like $sftp->stat('filename')['permissions'] & 0170000 == 0040000 I think. That's a hack borrowed from phpseclib itself:

https://github.com/phpseclib/phpseclib/blob/7a2c7a414c08d28f0700c7f6f8686a9e0e246a44/phpseclib/Net/SFTP.php#L1969

neubert
  • 15,947
  • 24
  • 120
  • 212