I have a folder named uploads
with a lot of files in it. I want to find out if there is a .zip
file inside it. How can i check if there is a .zip
file inside it with php?
Asked
Active
Viewed 1,098 times
-1

Jack Maessen
- 1,780
- 4
- 19
- 51
-
1[glob](http://php.net/glob) should do the trick, no? – Jonnix Jan 14 '19 at 14:13
-
1by using `glob($value.'/*.zip')` – devpro Jan 14 '19 at 14:13
-
3This question has like a dozen answers already on SO. Do the minimum amount of research before asking. – jibsteroos Jan 14 '19 at 14:15
-
Expanding the answer from Bernhard (credits to him) you can do regular checks like if (count ($result) > 0){ //your code } – Mbotet Jan 14 '19 at 14:19
3 Answers
3
This also could help, using scandir and pathinfo
/**
*
* @param string $directoryPath the directory to scan
* @param string $extension the extintion e.g zip
* @return []
*/
function getFilesByExtension($directoryPath, $extension)
{
$filesRet = [];
$files = scandir($directoryPath);
if(!$files) return $filesRet;
foreach ($files as $file) {
if(pathinfo($file)['extension'] === $extension)
$filesRet[]= $file;
}
return $filesRet;
}
it can be used like
var_dump(getFilesByExtension("uploads/","zip"));

Accountant م
- 6,975
- 3
- 41
- 61
3
Answer is already given by @Bemhard, i am adding more information for future use:
If you want to run script inside your uploads
folder than you just need to call glob('*.zip')
.
<?php
foreach(glob('*.zip') as $file){
echo $file."<br/>";
}
?>
If you have multiple folders and containing multiple zip files inside the folders, than you just need to run script from root.
<?php
$dir = __DIR__; // will get the exact path
$dirs = array_filter(glob('*'), 'is_dir'); // filter is directory or not.
$i = 1;
foreach ($dirs as $key => $value) {
foreach(glob($value.'/*.zip') as $file){
echo $file."<br/>"; // this will print all files inside the folders.
}
$i++;
}
?>
One Extra point, if you want to remove all zip files with this activity, than you just need to unlink
file by:
<?php
$dir = __DIR__; // will get the exact path
$dirs = array_filter(glob('*'), 'is_dir'); // filter is directory or not.
$i = 1;
foreach ($dirs as $key => $value) {
foreach(glob($value.'/*.zip') as $file){
echo $file."<br/>"; // this will print all files inside the folders.
unlink($file); // this will remove all files.
}
$i++;
}
?>

devpro
- 16,184
- 3
- 27
- 38