phpfilenamessftpphpseclib

Downloading file matching pattern using phpseclib


I am trying to download a file from a SFTP server. I have managed to connect to it and download the files. The problem is that the file in the server will be updated daily and part of the filename is the exact time when it is generated which is unpredictable.

How can I implement my PHP script so it downloads any XML file which name starts with a certain pattern but I don't know the exact full name?


Solution

  • You have to retrieve a list of all files in the remote directory using Net_SFTP::nlist.

    Then you iterate the list, finding a file name that matches your requirements.

    Then you download the selected file using Net_SFTP::get.

    include("Net/SFTP.php");
    
    $sftp = new Net_SFTP("host");
    
    if (!$sftp->login("username", "password"))
    {
        die("Cannot connect");
    }
    
    $path = "/remote/path";
    $list = $sftp->nlist($path);
    
    if ($list === false)
    {
        die("Error listing directory ".$path);
    }
    
    $prefix = "prefix";
    $matches = preg_grep("/^$prefix.*/i", $list);
    if (count($matches) != 1)
    {
        $s = implode(",", $matches);
        die("No file or more than one file matches the pattern: $s");
    }
    
    $matches = array_values($matches);
    $filename = $matches[0];
    $filepath = $path."/".$filename;
    if (!$sftp->get($filepath, $filename))
    {
        die("Error downloading file ".$filepath);
    }