Category: PHP Functions
Tutorial: How to Create a Zip File with PHP / MySQL
Recently I added a function to a CMS that I have been evolving to meet the needs of ereads.com. I needed to allow users to select items (in this case ebooks) from the system and then export files that are attached to the books. So lets get started!
What is a Zip File?
“Zip files (.zip or .zipx) are single files, sometimes called “archives”, that contain one or more compressed files. Zip files make it easy to keep related files together and make transporting, e-mailing, downloading and storing data and software faster and more efficient. The Zip format is the most popular compression format used in the Windows environment, and WinZip is the most popular compression utility. ” – winzip.com
What you need to know:
Arrays, MySQL, FTP file permissions
First:
First you need to set up the tables. This is a simplified way of how to do it:
Table Name: Books
| id | title | author | description | filename |
| 1 | The great book | TA baron Sr. | blah blah blah | greatbook.pdf |
| 2 | The greater book | TA baron Jr. | blah blah blah | greaterbook.pdf |
| 3 | The greatest book | TA baron III | blah blah blah | greatestbook.pdf |
Table Name: Book_Cart
| id | bookid | username |
| 1 | 2 | anthony |
| 2 | 3 | anthony |
Lets assume:
- that you have all the zip files in a folder called “files”.
- that you already have a way for users to add books to the cart.
- that you have a the username of the person creating the zip stored in a session variable
Second:
You need to setup a folder for the zip file to be created. Make sure that the permissions are set to 777 on that folder. in this example we will pretend the zip folder is called “zips”.
Third:
Here is the zip function:
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
You can place this code at the top of the folder or you can stick it inside your functions include file. Now we need to run some queries to add the requested files into a zip. In the following example the function above with be included as “zip_function.php”.
include "zip_function.php";
include "database_connect_file.php";
$username = $_SESSION['username'];
$locationFilename = "zips/Book_export.zip";
$get_all = "SELECT * FROM Book_Cart WHERE username='$username'";
$rstall = mysql_query($get_all);
$export_num = mysql_num_rows($rstall);
while ($r1 = mysql_fetch_assoc($rstall)) {
$bookid = $r1['bookid'];
$qry4 = "SELECT * FROM Books WHERE id LIKE '$bookid'";
$result4 = mysql_query($qry4);
while ($row4 = mysql_fetch_assoc($result4)) {
$filename = $row4['filename'];
$files[]= "files/$filename";
}
}
create_zip($files, $locationFilename, true);
echo '<a href="'.$locationFilename.'"> Click here to download PDFs </a><br><br>';
And that should do it. All the code I provided works on mediatemple.net webservers with PHP safe- mode turned off. I found that some other servers don’t allow the creation of zip files. However if the server is set up for it, this should work.
If you have any questions, post them in comments and I will do my best to answer them.
-AD
PHP Function: remove special characters from post data
Since I began programming 6 years ago I always had trouble with collecting data from forms. Users tend to copy and paste data into them, capturing special characters in the process. The special chars then end up in the mysql data as some random garbage, then it appears on the website as weird symbols.
A while back I asked a programmer friend of mine if he had a function that would help out with this. He did! I’ve been using it with the last 9 applications that I built, and it works every time.
Here is the function code:
if (!function_exists('cleanText')) {
function cleanText($str){
$str = str_replace("Ñ" ,"Ñ", $str);
//$str = preg_replace('/Ñ/g',"|Ñ|", $str);
//echo "Text BEGIN ".$str." --- ".bin2hex ("Ñ")."\n<BR>"; // d1
/*
for($i = 0 ; $i < strlen($str) ; $i++){
echo "".$str{$i}." - ". bin2hex ( $str{$i})."<BR>";
}
*/
$str = str_replace("ñ" ,"ñ", $str);
$str = str_replace("ñ" ,"ñ", $str);
$str = str_replace("Á","Á", $str);
$str = str_replace("á","á", $str);
$str = str_replace("É","É", $str);
$str = str_replace("é","é", $str);
$str = str_replace("ú","ú", $str);
$str = str_replace("ù","ù", $str);
$str = str_replace("Í","Í", $str);
$str = str_replace("í","í", $str);
$str = str_replace("Ó","Ó", $str);
$str = str_replace("ó","ó", $str);
$str = str_replace("“","“", $str);
$str = str_replace("”","”", $str);
$str = str_replace("‘","‘", $str);
$str = str_replace("’","’", $str);
$str = str_replace("—","—", $str);
$str = str_replace("–","–", $str);
$str = str_replace("™","™", $str);
$str = str_replace("ü","ü", $str);
$str = str_replace("Ü","Ü", $str);
$str = str_replace("Ê","Ê", $str);
$str = str_replace("ê","î", $str);
$str = str_replace("Ç","Ç", $str);
$str = str_replace("ç","ç", $str);
$str = str_replace("È","È", $str);
$str = str_replace("è","è", $str);
$str = str_replace("•","•" , $str);
return $str;
}
}
?>
Stick this in code in a page called “functions.php” and include it at the top of the page. It uses str_replace to replace special characters. You can add and remove characters easily by coping $str = str_replace(“•”,”•” , $str); and just replacing the character and the code when necessary.
Here’s a snip of it in action
HMTL Form:
<form method="post" action="clean_data.php"> <input type="text" name="textfield"> <input name="submit" type="submit" /> </form> clean_data.php: <?php include "includes/functions.php"; // Get post Data from form $textfield = $_POST["textfield"]; // Clean Data $textfield= cleanText($textfield); echo $textfield; ?>
And that’s all there is to it. If you have any questions, post them in the comments of this post.
-AD



