简体   繁体   中英

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?

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.

你也可以做$sftp->file_exists($directory)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM