3

I am using phpseclib to upload a file to a remote server. Previously, my script worked fine, but what I am expect is it can check whether the remote server has received the file or not. Such as if file existed return 1/true or if file no existed return 0/false.

My code:

include('Net/SFTP.php');

$path = "upload/";
$path_dir .=   $ref .".xml";
$directory = '/home/XML/';
$directory .=   $ref .".xml";

$sftp = new Net_SFTP('xxx.com',22);
if (!$sftp->login('username', 'password'))
{
    exit('SFTP Login Failed');
}
echo $sftp->pwd();

$sftp->put($directory, $path_dir, NET_SFTP_LOCAL_FILE);

if (!$sftp->get($directory))
{
    echo "0";
}

The file uploaded successfully, but don't know how to check the file which whether exists or not.

Does anyone have any ideas or suggestions for troubleshooting this?

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Rocky ZZ
  • 45
  • 1
  • 7

2 Answers2

7

You can use file_exists method:

if ($sftp->file_exists($directory))
{
    echo "File exists";
}

(The $directory variable name is really confusing here. It's a path to a file not directory.)

Though it is just enough to test result of the put method. The additional check is not really needed.


The file_exists method is available since phpseclib 0.3.7 only. If you are using an older version of phpseclib, use stat method:

if ($sftp->stat($directory))
{
    echo "File exists";
}

The file_exists internally calls the stat anyway.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
1

You could also do $sftp->file_exists($directory).

neubert
  • 15,947
  • 24
  • 120
  • 212
  • sorry, not working for me. not sure file_exists is sftp has file_exists as I cannot find it in the SFTP examples: [link](https://github.com/phpseclib/phpseclib/blob/master/phpseclib/Net/SFTP.php) but stat($directory) is working fine – Rocky ZZ Sep 24 '15 at 08:26
  • 1
    It's line 2250 of the link you provided: https://github.com/phpseclib/phpseclib/blob/master/phpseclib/Net/SFTP.php#L2250 – neubert Sep 24 '15 at 11:41