Armitage2k
Armitage2k

Reputation: 1254

PHP - select ONLY file in folder without foreach()?

I have a script that places a CSV file into a temporary folder where it will remain until another script picks it up for import into my DB. This is a separated script and for various reasons cannot do both the placement into the temp folder AND the consecutive database import.

Since I now have a separated import script, I first need to scan the temp folder and look for the import-file, which is the ONLY file in the folder anyway, but has a constantly changing filename that I cannot pre-define. My question now is, how can I get the filename of said file, assign it to a variable and use this later for the database import?

When using a foreach() loop I end up with an array, but rather would like a string for further usage.

PHP

if(file_exists('./'.$temp)) {
    $files = scandir('./'.$temp.'/');

    foreach ($files as $attachment) {
        if (in_array($attachment, array(".",".."))) continue;

        $import_file = $attachment;
    }
} else {
    die("Temp Folder for $temp could not be found, hence no files exist for import. Operation cancelled.");
}

Upvotes: 0

Views: 69

Answers (1)

toastrackengima
toastrackengima

Reputation: 8732

Since scandir is ordered alphabetically (http://php.net/manual/en/function.scandir.php), you file will always be at the end of the scandir array (on non-unix systems it is the only file, on unix systems it comes after . and ..).

Thus, you just need to get the last item of the array, like so:

$s = scandir("./".$temp."/");
$import_file = $s[count($s)-1];

This code automatically retrieves the name of the third file in the temp folder, so as long as there are no other files in there it should work perfectly.

Upvotes: 2

Related Questions