Using PHP ftp_get() to retrieve file with wildcard filename

后端 未结 2 661
日久生厌
日久生厌 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.

提交回复
热议问题