Rocky ZZ
Rocky ZZ

Reputation: 45

How to check uploaded file is exists with SFTP using phpseclib

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?

Upvotes: 3

Views: 7992

Answers (2)

Martin Prikryl
Martin Prikryl

Reputation: 202484

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.

Upvotes: 8

neubert
neubert

Reputation: 16802

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

Upvotes: 1

Related Questions