Using PHP ftp_get () to retrieve the file with the generic file name

advertisements

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()?


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