Using PHP ftp_get() to retrieve file with wildcard filename

后端 未结 2 634
日久生厌
日久生厌 2021-01-14 07:29

I have a file on an FTP with a dynamic filename. The schema looks something like:

ABCD_2_EFGH_YYMMDD_YYMMDD_randomnumber_.TXT

The dates (

相关标签:
2条回答
  • 2021-01-14 07:55

    The ftp_get can be used to download a single file only. No wildcards are supported.


    The only reliable way is to list all files, filter them locally and then download them one-by-one:

    $conn_id = ftp_connect("ftp.example.com") or die("Cannot connect");
    ftp_login($conn_id, "username", "password") or die("Cannot login");
    ftp_pasv($conn_id, true) or die("Cannot change to passive mode");
    
    $files = ftp_nlist($conn_id, "/path");
    
    foreach ($files as $file)
    {
        if (preg_match("/\.txt$/i", $file))
        {
            echo "Found $file\n";
            // download with ftp_get
        }
    }
    

    Some (most) servers will allow you to use a wildcard directly:

    $conn_id = ftp_connect("ftp.example.com") or die("Cannot connect");
    ftp_login($conn_id, "username", "password") or die("Cannot login");
    ftp_pasv($conn_id, true) or die("Cannot change to passive mode");
    
    $files = ftp_nlist($conn_id, "/path/*.txt");
    
    foreach ($files as $file)
    {
        echo "Found $file\n";
        // download with ftp_get
    }
    

    But that's a nonstandard feature (while widely supported).

    For details see my answer to FTP directory partial listing with wildcards.

    0 讨论(0)
  • 2021-01-14 08:13

    You can use ftp_nlist with pattern to retreive file names from ftp folder. And then use ftp_get in loop

    $fileList = ftp_nlist($conn_id, 'subdirectory_name/file_prefix_*.txt');
    
    for ($i = 0; $i < count($fileList); $i++) {
        $localFile = tempnam(sys_get_temp_dir(), 'ftp_in');
        if (ftp_get($conn_id, $localFile, $fileList[$i], FTP_BINARY)){
          //do something
        }
    }
    
    0 讨论(0)
提交回复
热议问题