Vineesh K S
Vineesh K S

Reputation: 1964

How to check a folder contains .csv files?

I need to check whether a folder contains csv files or not. Using PHP

I need to show an error message if someone try to upload any csv into a specific folder if there is already existing a csv.

Upvotes: 0

Views: 1717

Answers (5)

Tahajjat Tuhin
Tahajjat Tuhin

Reputation: 3

<?php

$directory = new DirectoryIterator(__DIR__);

if ($fileinfo->isFile()) {

$fileExt = $fileinfo->getExtension();

if($fileExt=="csv") { echo "File found"; } else { echo "File not found"; }

}

?>

Reference:[http://php.net/manual/en/directoryiterator.getextension.php]

Upvotes: 0

B.Kocaman
B.Kocaman

Reputation: 815

$dir = 'folder';
echo (count(glob("$dir/*.csv")) === 0) ? 'Empty' : 'Not empty';

You can use glob() function. http://php.net/manual/tr/function.glob.php

Also @Barmar answer is look like doing job well.

Upvotes: 0

Sahil Gulati
Sahil Gulati

Reputation: 15141

Loop over the files of directory to check whether it contains csv or not.

$files=scandir("/path/to/dir");
foreach($files as $fileName)
{
    if(preg_match("/\.csv$/", $fileName))
    {
        throw new Exception("/path/to/dir contains csv file with filename: $fileName");
    }
}

Upvotes: 0

Barmar
Barmar

Reputation: 781088

Use glob() to find all files matching a wildcard. It returns an array of the matches, so you can check if the array is empty.

$files = glob("$dirname/*.csv");
if (!empty($files)) {
    die("Error: The directory already has a .csv file");
}

Upvotes: 3

Andreas
Andreas

Reputation: 105

<?php
$filename = '/path/to/foo.txt';

if (file_exists($filename)) {
    echo "Die Datei $filename existiert";
} else {
    echo "Die Datei $filename existiert nicht";
}
?>

From: http://php.net/manual/de/function.file-exists.php

Upvotes: 0

Related Questions