PHP Remove all Files From a Directory - Exclude File Extension - php

I am trying for the life of me to find the best way to delete all files in a single directory excluding a single file extension, ie anything that is not .zip
The current method I have used so far which successfully deletes all files is:
$files = glob('./output/*');
foreach($files as $file)
{
if(is_file($file))
unlink($file); // delete file
}
I have tried modifying this like so:
$files = glob('./output/**.{!zip}', GLOB_BRACE);
foreach($files as $file)
{
if(is_file($file))
unlink($file); // delete file
}
However, I am not hitting the desired result. I have changed the line as follows which has deleted only the zip file itself (so I can do the opposite of desired).
$files = glob('./output/*.{zip}', GLOB_BRACE);
I understand that there are other methods to read directory contents and use strpos/preg_match etc to delete accordingly. I have also seen many other methods, but these seem to be quite long winded or intended for recursive directory loops.
I am certainly not married to glob(), I would simply like to know the simplest/most efficient way to delete all files in a single directory that are not a .zip file.
Any help/advice is appreciated.

$exclude = array("zip");
$files = glob("output/*");
foreach($files as $file) {
$extension = pathinfo($file, PATHINFO_EXTENSION);
if(!in_array($extension, $exclude)) unlink($file);
}
This code works by having an array of excluded extensions, it loads up all files in a directory then checks for the extension of each file. If the extension is in the exclusion list then it doesn't get deleted. Else, it does.

This should work for you:
(I just use array_diff() to get all files which are different to *.zip and then i go through these files and unlink them)
<?php
$files = array_diff(glob("*.*"), glob("*.zip"));
foreach($files as $file) {
if(is_file($file))
unlink($file); // delete file
}
?>

How about calling to the shell? So in Linux:
$path = '/path/to/dir/';
$shell_command = escapeshellcmd('find ' . $path .' ! -name "*.zip" -exec rm -r {}');
$output = shell_exec($shell_command);

I would simply like to know the simplest/most efficient way to delete all files in a single directory that are not a .zip file.
SPL Iterators are very effective and efficient.
This is what I would use:
$folder = __DIR__;
$it = new FilesystemIterator($folder, FilesystemIterator::SKIP_DOTS);
foreach ($it as $file) {
if ($file->getExtension() !== 'zip') {
unlink($file->getFilename());
}
}

Have you tried this:
$path = "dir/";
$dir = dir($path);
while ($file = $dir->read()) {
if ($file != "." && $file != ".." && substr($file, -4) !== '.zip') {
unlink($file);
}
}

Related

How to delete file in PHP

I want to delete files in a specific directory in PHP. How can I achieve this?
I have the following code but it does not delete the files.
$files = array();
$dir = dir('files');
while ($file = $dir->read()) {
if ($file != '.' && $file != '..') {
$files[] = $file;
}
unlink($file);
}
I think your question isn't specific, this code must clear all files in the directory 'files'.
But there are some errors in that code I think, and here is the right code:
$files= array();
$dir = dir('files');
while (($file = $dir->read()) !== false) { // You must supply a condition to avoid infinite looping
if ($file != '.' && $file != '..') {
$files[] = $file; // In this array you push the valid files in the provided directory, which are not (. , ..)
}
unlink('files/'.$file); // This must remove the file in the queue
}
And finally make sure that you provided the right path to dir().
You can get all directory contents with glob and check if the value is a file with is_file() before unlinking it.
$files = glob('files/*'); // get directory contents
foreach ($files as $file) { // iterate files
// Check if file
if (is_file($file)) {
unlink($file); // delete file
}
}
If you want to remove files matching a pattern like .png or .jpg, you have to use
$files = glob('/tmp/*.{png,jpg}', GLOB_BRACE);
See manual for glob.

Unlink all but one filetype

How can I remove ALL but .sql file extensions in a specific folder with php? It's a php file that is supposed to create a backup of the database and place it in a back up folder but if there are any .jpg or any other extensions it should remove them from the backup folder.
You can use glob:
$path = "backup/";
foreach(glob($path ."*.*") as $file) {
$location = explode(".",$file);
$extension = $location[count($location)-1];
if($extension != "sql"){
unlink($file);
}
}
One liner:
foreach(glob("backup/*") as $file) {
if(pathinfo($file, PATHINFO_EXTENSION) != "sql") unlink($file);
}
foreach (glob("/path/to/folder/*") as $filename) {
if(!pathinfo($filename)['extension'] == "sql"){
unlink($filename);
}
}
We use glob to final all files (*) inside /path/to/folder/
Then we check is the file extension isn't sql using !pathinfo($filename)['extension'] == "sql", if true, we delete the file.

Deleting ".part" files from folder with PHP

I'm using the following to delete all files from the specified directory.
$files = glob('path/to/temp/*');
foreach($files as $file){
if(is_file($file))
unlink($file);
}
It removes everything other than partially uploaded files eg : myfile.mp3.part
I've tried specifying .part in the file path just to see if I can force it that way :
$files = glob('path/to/temp/*.part');
But that doesn't work either.
Am I missing something here? Is there a different method for deleting non-active partial files?
$files = scandir('/path/to/temp');
foreach($files as $key => $file) {
if ( preg_match('/.*?\.part$/', $file) ) {
unlink($file);
}
}
I'm using something likes this to delete all files in a folder.
$dir = "/path/to/temp";
$files = scandir($dir);
foreach($files as $file){
$path = $dir."/".$file;
if(is_file($path)) unlink($path);
}

PHP ZIP creating subfolders as files

I have some PHP code that I am using to try and zip a folder. The folder has two subfolders in it and several individual files.
Here is the code: -
<?php
$src = $_POST['srcin'];
$dst = $_POST['dstin'];
$zip = new ZipArchive;
$zip->open($dst, ZipArchive::CREATE);
if (false !== ($dir = opendir($src)))
{
while (false !== ($file = readdir($dir)))
{
if ($file != '.' && $file != '..')
{
$ans = DIRECTORY_SEPARATOR;
$zip->addFile($src.DIRECTORY_SEPARATOR.$file);
}
}
}
else
{
die('Can\'t read dir');
}
$zip->close();
echo json_encode('Folder Compressed');
?>
The input values are: -
srcin = "TestFolder"
dstin = "TestFolder.zip".
What is happening is that I am getting a zip file. However, the subfolders are being created as files.
I got the above code from searching this forum on how to ZIP a folder, yet I cannot see anything mentioned regarding subfolders not being zipped properly.
Any help is much appreciated.
Thanks
Martin
You should create a directory with addEmptyDir before you add a file to it.
Here is an example(see top comment) how to archive a directory recursively

Get a list of files and filenames without an extention using php

I'm trying to make a jQuery slider that automatically loads all the images in a specified folder. So I'm using a small PHP script that makes a list of all the files in that directory. For the captions of the slider I wanted to use the filename (without extension).
I'm using the following script, using PHP. It can list all the files with the extensions, but I can't find a way to also display the filename (for the captions) without the extensions.
Anyone an idea?
Thanks in advance!
<?
$path = "img";
$dir_handle = #opendir($path) or die("Unable to open $path");
while ($file = readdir($dir_handle)) {
if($file == "." || $file == ".." || $file == "index.php" )
continue;
echo "$file";
}
closedir($dir_handle);
?>
Here you have more OO way:
$iterator = new DirectoryIterator($directory);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
$fileinfo->getBasename('.' .$fileinfo->getExtension());
}
}
You can get the filename without its extension using pathinfo():
$filename = pathinfo( $file, PATHINFO_FILENAME);

Categories