Reputation: 15
I need to get a file based on the second half of the filename with PHP
The structure of the filename will always be NAME_123456789.dat where the number is a tracking_id(unique)
.
The name being John, Mel, Bronson, etc
. And the number being a tracking_id
.
What the process will be just for comprehension is that a person will enter their tracking_id. it will extract that from the search bar and plant it in the ftp search in the specific directory. Because the tracking_id
is unique it should only return one result, hence ftp_get()
right?
Any help is greatly appreciated.
Upvotes: 1
Views: 547
Reputation: 164767
Given the relatively small directory size (100+ from comments above), you should be ok first using ftp_nlist()
to list all the files and then searching for and downloading the file you want.
$search = '_' . $trackingId . '.dat';
$searchLen = strlen($search);
$dir = '.'; // example directory
$files = ftp_nlist($connection, $dir);
foreach ($files as $file) {
// check if $file ends with $search
if (strrpos($file, $search) === strlen($file) - $searchLen) {
// found it, download it
ftp_get($connection, 'some/local/file/path', $dir . '/' . $file);
}
}
Better and more future-proof options can be found in Michael Berkowski's comment above...
How many files do you expect to be operating in the directory at any given time? If it is a small number, listing the contents via ftp may work suitably. If it is many thousands of files, you might want to store some sort of text manifest file to read from, or index them in a database.
These do hinge on how and when the files are uploaded to the FTP server though so given we don't know anything about that, I cannot provide any solutions.
Upvotes: 1