Search code examples
phpfgetcsvscandir

Failed to read csv file from a server directory in PHP


In the server, there are some csv file. I want to get all the csv file in an array and then read the last updated csv file from the array. And then, I want to keep the last updated CSV data into an array. I get all the filename from the directory. But I cannot able to read the csv file. How can I solve this?

Here is my code.

//directory
$dir = DATA_DIR . '/' . date("Y") . '/' . date("md");

//copy filenames to array
$files = array();
$files = glob($dir."/*.csv");

// sort files by last modified date
usort($files, function($x, $y) {
    return filemtime($x) < filemtime($y);
});

$baseFile = [];

foreach($files as $file) {

    if (($handle = fopen($file, "r")) !== FALSE) {
        $baseFile[] = basename($file);

    } else {
        echo "Could not open file: " . $file;
    }

}

print_a($baseFile);

// output of baseFile array
/*
Array(
[0] => 34342658.csv
[1] => 34342325.csv
[2] => 34342007.csv
[3] => 34341709.csv
[4] => 34341407.csv
[5] => 34341077.csv
[6] => 34340752.csv

.............)
*/

// print the last updated csv file name
print_a($baseFile[0]);
// output: 34342658.csv

$csvFile = file($baseFile[0]);
print_a($csvFile);

Solution

  • You have a mistake. $baseFile array contains only file names, not the paths. You must use full path when you call file(...) function.

    In your case it should be:

    $csvFile = file($dir . '/' . $baseFile[0]);
    

    Also just a notice - you call fopen() many times but never close the handlers. You should call fclose() each time to not leave a bunch of opened descriptors.