Reputation: 1964
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
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
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
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
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
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