Using PHP ftp_get() to retrieve file with wildcard filename

吃可爱长大的小学妹 提交于 2020-07-03 03:43:11

问题


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 (YYMMDD) reflect the previous day and current day and the randomnumber value is a count of the records in the file and varies each day.

I am attempting to retrieve the file using PHP but I am having trouble using a wildcard name. Here is a sample of the code:

<?php
$yesterday = strtotime('-1 day', time());
$today = strtotime('-0 day', time());
$local_file = "ABCD_2_EFGH__".date('Y-m-j', $yesterday).".txt";
$server_file = "ABCD_2_EFGH_".date('ymd', $yesterday)."_".date('ymd', $today)."_*.txt";

$conn_id = ftp_connect(ftpaddress);
$login_result = ftp_login($conn_id, 'username', 'password');
ftp_chdir($conn_id, 'subdirectory name');
ftp_get($conn_id, $local_file, $server_file, FTP_BINARY);
?>

When running this code i get the following error:

ftp_get() expects parameter 3 to be a valid path

I have also tried using glob() for $server_file and receive the same error.

Does anyone know how to use dynamic filenames with ftp_get()?


回答1:


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
    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/29308061/using-php-ftp-get-to-retrieve-file-with-wildcard-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!