Creating a zip from a folder full of files can be done in PHP using the ZipArchive class. This class instance creates a handle to read or write files to a compressed archive.
This class includes several properties and methods to zip file archives.
This file parses the input directory and compresses its files into a zip file. It proceeds with the following steps to create the zip file of a directory.
Create a PHP ZipArchive class instance.
Open a zip file archive with the instance. It accepts the output zip file name and the mode to open the archive.
Apply a recursive parsing in the input directory.
If the directory includes a file, then it adds to the zip archive using addFile().
It handles the use cases of getting the possibilities of being unable to read or archive the directory. Once the zip is created, it displays a message to the browser.
create-zip-file.php
<?php
// Important: You should have read and write permissions to read
// the folder and write the zip file
$zipArchive = new ZipArchive();
$zipFile = "./example-zip-file.zip";
if ($zipArchive->open($zipFile, ZipArchive::CREATE) !== TRUE) { exit("Unable to open file.");
}
$folder = 'example-folder/';
createZip($zipArchive, $folder);
$zipArchive->close();
echo 'Zip file created.'; function createZip($zipArchive, $folder)
{ if (is_dir($folder)) { if ($f = opendir($folder)) { while (($file = readdir($f)) !== false) { if (is_file($folder . $file)) { if ($file != '' && $file != '.' && $file != '..') { $zipArchive->addFile($folder . $file); } } else { if (is_dir($folder . $file)) { if ($file != '' && $file != '.' && $file != '..') { $zipArchive->addEmptyDir($folder . $file); $folder = $folder . $file . '/'; createZip($zipArchive, $folder); } } } } closedir($f); } else { exit("Unable to open directory " . $folder); } } else { exit($folder . " is not a directory."); }
}
?>
Output
//If succeeded it returns Zip file created. //If failed it returns Unable to open directory example-folder.
[or] "example-folder is not a director.
How to download the compressed zip file
In the last step, the zip file is created using the PHP ZipArchive class. That zip file can be downloaded by using the PHP code below.
It follows the below steps to download the zip file created.
Get the absolute path of the zip file.
Set the header parameters like,
Content length.
Content type.
Content encoding, and more.
download-zip-file.php
<?php
$filename = "example-zip-file.zip";
if (file_exists($filename)) { // adjust the below absolute file path according to the folder you have downloaded // the zip file // I have downloaded the zip file to the current folder $absoluteFilePath = __DIR__ . '/' . $filename; header('Pragma: public'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Cache-Control: private', false); // content-type has to be defined according to the file extension (filetype) header('Content-Type: application/zip'); header('Content-Disposition: attachment; filename="' . basename($filename) . '";'); header('Content-Transfer-Encoding: binary'); header('Content-Length: ' . filesize($absoluteFilePath)); readfile($absoluteFilePath); exit();
}
?>
<div class='container'> <h2>Create and Download Zip file using PHP</h2> <p> <a href="create-zip-file.php">Create Zip File</a> </p> <p> <a href="download-zip-file.php">Download Zip File</a> </p>
</div>
Tales Of Symphonia Remastered Coming To Nintendo Switch In 2023
Announced during the Nintendo Direct, Tales of Symphonia Remastered will launch on Nintendo Switch in early 2023. Originally released on the Nintendo GameCube, the game follows Llyod and Colette, as they journey to save the world from darkness.
They will meet a number of allies along their journey, like the wondering aristocrat Zelos and Presea, a lumberjack who lost her emotions. Together they will make sure that Colette, the current chosen one, can climb the Tower of Salvation and defeat the evil Desians. Tales of Symphonia Remastered will feature up to four player co-op for its real-time combat, letting you and your friends cast magic and defeat enemies together.
From the creators of theHunter: Call of the Wild comes a genre-defying fishing experience! Explore a vast and atmospheric open world in search of the perfect fishing spot. Ride the open waters alone or with friends and embark on your journey to become a master angler.
Challenge: Given a Python list of strings and a query string. Find the strings that partially match the query string.
Example 1:
Input: ['hello', 'world', 'python'] and 'pyth'
Output: ['python']
Example 2:
Input: ['aaa', 'aa', 'a'] and 'a'
Output: ['aaa', 'aa', 'a']
Example 3:
Input: ['aaa', 'aa', 'a'] and 'b'
Output: []
Let’s dive into several methods that solve this and similar type of problems. We start with the most straightforward solution.
Method 1: Membership + List Comprehension
The most Pythonic way to find a list of partial matches of a given string query in a string list lst is to use the membership operator in and the list comprehension statement like so: [s for s in lst if query in s].
Here’s a simple example:
def partial(lst, query): return [s for s in lst if query in s] # Example 1:
print(partial(['hello', 'world', 'python'], 'pyth'))
# ['python'] # Example 2:
print(partial(['aaa', 'aa', 'a'], 'a'))
# ['aaa', 'aa', 'a'] # Example 3:
print(partial(['aaa', 'aa', 'a'], 'b'))
# []
In case you need some background information, feel free to check out our two tutorials and the referenced videos.
To find a list of partial query matches given a string list lst, combine the membership operator with the filter() function in which you pass a lambda function that evaluates the membership operation for each element in the list like so: list(filter(lambda x: query in x, lst)).
Here’s an example:
def partial(lst, query): return list(filter(lambda x: query in x, lst)) # Example 1:
print(partial(['hello', 'world', 'python'], 'pyth'))
# ['python'] # Example 2:
print(partial(['aaa', 'aa', 'a'], 'a'))
# ['aaa', 'aa', 'a'] # Example 3:
print(partial(['aaa', 'aa', 'a'], 'b'))
# []
Generally, I like list comprehension more than the filter() function because the former is more concise (e.g., no need to convert the result to a list) and slightly faster. But both work perfectly fine!
Method 3: Regex Match + List Comprehension
The most flexible way to find a list of partial query matches given a string list lst is provided by Python’s powerful regular expressions functionality. For example, the expression [x for x in lst if re.match(pattern, x)] finds all strings that match a certain query pattern as defined by you.
The following examples showcase this solution:
import re def partial(lst, query): pattern = '.*' + query + '.*' return [x for x in lst if re.match(pattern, x)] # Example 1:
print(partial(['hello', 'world', 'python'], 'pyth'))
# ['python'] # Example 2:
print(partial(['aaa', 'aa', 'a'], 'a'))
# ['aaa', 'aa', 'a'] # Example 3:
print(partial(['aaa', 'aa', 'a'], 'b'))
# []
In this example, we use the dummy pattern .*query.* that simply matches words that contain the query string. However, you could also do more advanced pattern matching—regex to the rescue!
Again, I’d recommend you check out the background info on regular expressions:
Conspiracy Corner Bundle | 6 Steam Games | 94% OFF
[www.indiegala.com] Are we living in a simulation...or are we simulating life...via videogames? Investigate, explore, deduce and uncover conspiracies with the following indie games: Who Stole My Beard?, Just Take Your Left, The Corridor: On Behalf Of The Dead, Fhtagn! - Tales of the Creeping Madness, Abetot Family Estate, NMNE.
Ubisoft Reveals New Details On Its Assassin's Creed Netflix Series
Ubisoft and Netflix are working together on an Assassin's Creed live-action TV series, as was confirmed back in 2020. More details on the project emerged at Ubisoft Forward today, with Marc-Alexis Cote of Ubisoft Quebec confirming the show is "still early in development."
Ubisoft Film and Television is producing the show alongside Netflix and showrunner Jeb Stuart. Stuart wrote the iconic action movies Die Hard and The Fugitive, and more recently wrote Netflix TV show Vikings: Valhalla.
"It's gonna be an epic, genre-bending live-action adaptation of our video game series," Cote said. Along with the show, Ubisoft is also releasing an Assassin's Creed mobile game with Netflix Games.
Scathe is an intense, classic FPS with big guns and even bigger demons. You are Scathe, Enforcer of the Legions of Hell, forged from the earth by the Divine Creator himself. And you, like your fallen kin before you, must prove your worth by navigating a deviously crafted maze, entangled with demonic evil at every twist and turn. So, grab your Hell Hammer and get ready to unleash your almighty fury!
Use Scathe's brute strength and extreme speed to purge your way through Hell's most grotesque abominations, as you search for the Hellstones and defeat the all-powerful Guardians that protect them.
Posted by: xSicKxBot - 09-11-2022, 08:12 AM - Forum: Python
- No Replies
Python TypeError ‘set’ object is not subscriptable
5/5 – (1 vote)
Minimal Error Example
Given the following minimal example where you create a set and attempt to access an element of this set using indexing or slicing:
my_set = {1, 2, 3}
my_set[0]
If you run this code snippet, Python raises the TypeError: 'set' object is not subscriptable:
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 2, in <module> my_set[0]
TypeError: 'set' object is not subscriptable
Why Does the Error Occur?
The Python TypeError: 'set' object is not subscriptable occurs if you try to access an element of a set using indexing or slicing that imply an ordering of the set.
However, sets are unordered collections of unique elements: they have no ordering of elements. Thus, you cannot use slicing or indexing, operations that are only possible on an ordered type.
How to fix the TypeError: 'set' object is not subscriptable?
To fix the TypeError: 'set' object is not subscriptable, either convert the unordered set to an ordered list or tuple before accessing it or get rid of the indexing or slicing call altogether.
Here’s an example where you convert the unordered set to an ordered list first. Only then you use indexing or slicing so the error doesn’t occur anymore:
Posted by: xSicKxBot - 09-11-2022, 08:12 AM - Forum: Lounge
- No Replies
Best NBA 2K23 PFs: Top Power Forwards By Rating
NBA 2K23 is finally here, which means it's time to discuss the league's best power forwards. Barkley or Malone? Duncan or Webber? Dirk or Gasol? This year's list of NBA strong forwards has a lot more talent than you think and with Paolo Banchero being the Rookie Of The Year favorite, we wanted to find out the answers for ourselves. 2K23 ratings are in the wild and if you're curious about who's on the rise, here's everything you need to know about the 10 Best power forwards in NBA 2K23.