Category: Programming
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
A simple way to hide your wordpress website until launch.
Recently I had to revamp a website for a client. The website was using Word Press to power it and so I had to do some template editing that would make the website look very broken while I was experimenting. What I did was stop Word Press from running at all unless a get request happened.
To do this you must first find “index.php” in the root folder on your blog. It should look empty aside from loading the blog header. Then you paste in this code:
<?php
$display = $_GET['display'];if ($display !== “yes”) {
echo ‘Post a polite message letting the user know that the site is being worked on, you may use HTML in this space’;
exit();
}?>
After saving and uploading your modified index page, you will only see the message that you are echoing. If you want to see the wordpress blog you need to include ?display=yes at the end of your URL.
example: http://mysite.com/blog/?display=yes
Now you are free to experiment with the CSS without worrying about any users seeing the website break. If you have any questions about this, ask them in the comments.
-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
Intro to PHP: 01 “the echo”
If your just getting into PHP you first need to know how it works. PHP actually creates HTML on the server side before the user loads the page. PHP is in charge of checking for arguments, getting data from databases and sending emails. PHP is also capable of much more if modules are installed on the server.

Getting your feet wet:
What you need to know:
- HTML
- FTP
- An understanding of how web servers work.
PHP lets us do things that HTML does not. Let’s go through some basics.
<?php
echo “some stuff!”;
?>
To tell the webserver that you are using PHP you need to start with a <?php. You follow it with your code, then close it with ?>. Using echo tells PHP that we want to spit something into the HTML. You can echo anything. Javascripts, style sheets, anchor tags, and anything else that is valid in HTML.
what makes this important is the arguments that you use in PHP.
<?php
if ($this_variable==”HAPPY”) {
echo ‘<link rel=”stylesheet” type=”text/css” href=”css/SUPER_HAPPY_STYLE.css”>’;
}
else {
echo ‘<link rel=”stylesheet” type=”text/css” href=”css/SUPER_SADFACE_STYLE.css”>’;
}
?>
What the argument above is doing is checking a variable, and if it’s set to “Happy” then it will tell the page to use the happy style sheet, if its not, set it to the sad style sheet. This little snip of code could be used to let your visitors change the websites theme. I’ll cover variables next time!
-AD



