-1

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?

Jack Maessen
  • 1,780
  • 4
  • 19
  • 51

3 Answers3

3

Use the glob() function.

$result = glob("my/folder/uploads/*.zip");

It will return an array with the *.zip-files.

Cid
  • 14,968
  • 4
  • 30
  • 45
Bernhard
  • 1,852
  • 11
  • 19
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++;
}
?>

References: Unlink Glob

devpro
  • 16,184
  • 3
  • 27
  • 38