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
Related
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.
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);
}
}
I need to get the contents of several files within a directory but which is the best way of doing this?
I am using
$data = file_get_contents('./files/myfile.txt');
but I want every file without having to specify the file individually as above.
You can use glob to get particular file extention and file_get_contents to get the content
$content = implode(array_map(function ($v) {
return file_get_contents($v);
}, glob(__DIR__ . "/files/*.txt")));
/**
* Change the path to your folder.
* This must be the full path from the root of your
* web space. If you're not sure what it is, ask your host.
*
* Name this file index.php and place in the directory.
*/
// Define the full path to your folder from root
$path = "/home/content/s/h/a/shaileshr21/html/download";
// Open the folder
$dir_handle = #opendir($path) or die("Unable to open $path");
// Loop through the files
while ($file = readdir($dir_handle)) {
$data = file_get_contents('$filet');
}
// Close
closedir($dir_handle);
You can dir the directory and loop through it to get the contents of all files.
<?php
$path = './files';
$d = dir($path);
$contents = '';
while (false !== ($entry = $d->read())) {
if (!($entry == '..' || $entry == '.')) {
$contents .= file_get_contents($path.'/'.$entry);
}
}
$d->close();
?>
If you only want .txt files you can change the if statement of the code above from:
if (!($entry == '..' || $entry == '.')) {
to:
if (substr($entry, -4) == '.txt') {
This will result to a variable $contents that is type string and has all the contents of all the files (or only txt files if you select the 2nd solution) that are in the ./files dir.
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);
See this question. I can't use that code:
function addFolderToZip($dir, $zipArchive, $zipdir = ''){
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
//Add the directory
$zipArchive->addEmptyDir($dir);
// Loop through all the files
while (($file = readdir($dh)) !== false) {
//If it's a folder, run the function again!
if(!is_file($dir . $file)){
// Skip parent and root directories
if( ($file !== ".") && ($file !== "..")){
addFolderToZip($dir . $file . "/", $zipArchive, $zipdir . $file . "/");
}
}else{
// Add the files
$zipArchive->addFile($dir . $file, $zipdir . $file);
}
}
}
Please write an example for me. The second problem is too complex.
When I use addfile function it will add and appear in the archive as a file and this great. Now when I use:
$z = new ZipArchive();
$z->open('test.zip')
for ($i=0; $i< $z->numFiles;$i++) {
$aZipDtls = $z->statIndex($i);
echo $aZipDtls['name'];
}
it now shows if I add a file in folder like that:
$zip->addFile('/path/to/index.txt', 'dir/newname.txt');
it show in the Winrar soft a dir then a file but in the code it shows it as one file.
Like that in winrar:
dir/
dir/newname.txt
In my PHP system, just only show one file without its dir, like that:
dir/newname.txt
This mean it's impossible to add a new file in a dir.
Difficult to know what you want, but here goes:
<?php
$zip = new ZipArchive();
$zip->open('test.zip');
$zip->addFile('/path/to/newname.txt','dir/newname1.txt');
$zip->addFile('/path/to/newname.txt','dir/newname2.txt');
$zip->addFile('/path/to/newname.txt','dir/dir/newname3.txt');
$zip->addFile('/path/to/newname.txt','dir/dir/dir/newname4.txt');
for ($i=0; $i< $zip->numFiles;++$i) {
$aZipDtls = $zip->statIndex($i);
echo $aZipDtls['name'],"\n";
}
$zip->close();
?>
Should cover all questions. That will unzip with exactly the structure you'd expect it to. The discrepancy is likely due to the way WinRar displays the archive structure.