Category Archives: Website Development
ZIP Archive Manipulation
In this tutorial we will look in detail into the ZIP functions included in PHP. So what is a ZIP Archive?
DEFINITION
The ZIP file format (.zip) is a data compression and archive format. A ZIP file contains one or more files that have been compressed to reduce file size, or stored as-is.
Creating A ZIP File
First we need some files or information we want to compress into the ZIP. Below are some examples of what I have included in this tutorial. These files should be placed in the directories stated.
test_files/test_text.txt
test_files/test_html.html
test_document.doc
You can download copies of the test files I have used by clicking on the link at the bottom of this tutorial.
So now we have the files we are going to include in the archive, let’s go through the functions we will be using in this tutorial.
OPEN
open(string $filename [, int $flags]); Open is used to open a new ZIP Archive for reading, writing or modifying.
ADDFROMSTRING
addFromString(string $local_file_name, string $contents); addFromString is used to include data into the ZIP Archive that is not already located inside a file. So this function will create a file inside the archive and insert the string contents into that file.
ADDFILE
addFile(string $file_name_archive, string $file_name_local); addFile is used to include an already existing file or folder into the archive.
Now we will start by constructing the string variables.
$zip_archive = "new_zip_archive.zip"; $folder_local_location = "test_files/"; $folder_in_archive = "test_files/"; $file_local_location = "test_document.doc"; $file_in_archive = "test_document.doc";
$zip_archive is the string for setting the filename and location of the ZIP Archive you are creating. E.g “/zips/zipzippyzip.zip” but this archive must be in a directory that is writable or must already exist and have writable permissions.
$folder_local_location is the name and location of the folder we are including into the archive that already exists on the server.
$folder_in_archive is the name and location of the folder we are adding into the archive this is useful as you can rename the folder once inside the ZIP Archive.
$file_local_location is the name and location of the file we are including into the archive that already exists on the server.
$file_in_archive is the name and location of the folder we are adding into the archive this is useful as you can rename the folder once inside the ZIP Archive.
Next we must create the ZIP Archive class and open it for creation.
$zip = new ZipArchive; $open = $zip->open($zip_archive, ZipArchive::CREATE);
In the first line we are starting the ZipArchive class and assigning the class the $zip variable this is so we can implement it in other locations as you will see in line 2.
Now we must run an, IF command to check whether the $open has outputted TRUE successfully. This uses a comparison operator of === this means Identical where as == just means Equal. For more information about operators visit the php.net website.
http://www.php.net/manual/en/language.operators.php
if ($open === TRUE) {
Once we have confirmed $open has been successful, we can commence with inserting items into the ZIP Archive. Using the commands we learnt previously.
$zip->addFromString('new_string_file.txt', 'This file has been created via PHP and will be put into the ZIP Archive.');
$zip->addFile($file_in_archive, $file_local_location);
$zip->addFile($folder_in_archive, $folder_local_location);
$zip->close();
After we have inserted the items we must close the archive this finishes the ZIP Archive but as a final check we will see if the ZIP Archive actually exists in the location specified at the start and output the appropriate response.
if(file_exists($zip_archive)){
echo "Created Archive.";
}else{
echo "Error: Archive Does Not Exist.";
}
And finally the last bit of the code remember the if($open === TRUE){ well we must put the closing bracket and what happens if it doesn’t equal true.
} else {
echo "Unknown Error.";
}
Now we have completed the tutorial below is the finished product.
<?php
$zip_archive = "new_zip_archive.zip";
$folder_local_location = "test_files/";
$folder_in_archive = "test_files/";
$file_local_location = "test_document.doc";
$file_in_archive = "test_document.doc";
$zip = new ZipArchive;
$open = $zip->open($zip_archive, ZipArchive::CREATE);
if ($open === TRUE) {
$zip->addFromString('new_string_file.txt', 'This file has been created via PHP and will be put into the ZIP Archive.');
$zip->addFile($file_in_archive, $file_local_location);
$zip->addFile($folder_in_archive, $folder_local_location);
$zip->close();
if(file_exists($zip_archive)){
echo "Created Archive.";
}else{
echo "Error: Archive Does Not Exist.";
}
} else {
echo "Unknown Error.";
}
?>
Well now you’ve got through the difficult part of creating and inserting the items into a ZIP Archive. We need to be able to get the items out again. This is where the next part of the tutorial kicks in.
Extracting A ZIP File
To extract a ZIP we must first set a few string settings.
$zip_archive = "new_zip_archive.zip"; $extract_location = "new_zip_archive_extract/";
$zip_archive is the location and name of the archive we are going to extract in this case it is set to new_zip_archive.zip.
$extract_location is the location of where we want the files in the archive to be extracted to.
Now we must use the same commands as used as when creating the archive by creating a new ZipArchive class and assigning it to $zip then opening it and assigning it to $extract although this time without any flags selected. We must then use an IF statement to see if $extract outputs TRUE.
$zip = new ZipArchive;
$extract = $zip->open($name_of_zip);
if ($extract === TRUE) {
In this next section we will use a new command called extractto
EXTRACTTO extractTo(string $destination, mixed $entries); extractTo is used to export the files from within the ZIP Archive. The $entries can be written as just a single string or as an array. This is used to remove just certain files from the archive.
Now to use this function.
$zip->extractTo($extract_location); $zip->close(); echo 'Successfully Extracted.';
As again we have extracted the files using the extractTo function and then closed the ZIP Archive. We have then echoed the success message. Once we have done this we must finish off the IF statement we began previously. Although this time we will also output the error message if one is needed.
} else {
echo 'Error: ' . $extract;
}
So that’s it below is the overall code you should end up with.
<?php
$zip_archive = "new_zip_archive.zip";
$extract_location = "new_zip_archive_extract/";
$zip = new ZipArchive;
$extract = $zip->open($name_of_zip);
if ($extract === TRUE) {
$zip->extractTo($extract_location);
$zip->close();
echo 'Successfully Extracted.';
} else {
echo 'Error: ' . $extract;
}
?>
Now you have learnt how to create and extract a ZIP Archive using PHP. Please use this as a guide to further your learning but mess about with the functions available at the php.net website and see what you can come up with.
http://uk3.php.net/manual/en/class.ziparchive.php
To download the test files listed above visit.
http://www.peter-kelly.com/downloads/zip_test_files.zip
If you have any further questions on this Tutorial or anything else about myself or the content displayed on my website http://www.peter-kelly.com please don’t hesitate to contact me by emailing me@peter-kelly.me or by visiting my website.
Thank You for Reading.
Form Handling
In this tutorial we will be looking in detail into how to design a simple form and what methods we can use to process the data submitted. We will then advance onto creating a contact form which emails the results onto a specified email address.
Designing an HTML Form
First we have to start off the form structure. This is done by using the tags.
<form action="form_submit.php" method="post"> </form>
<form></form>as the simple starting and ending tags. But as you can see there are attributes inside the starting tag these are just some of the attributes that are available. Here is what the attributes I have used mean.
ACTION
Action is used to show where the form will be processed. In our case it will submit the form and the details to form_submit.php if the action is left blank it will indicate that the form is being processed on the same page as the form.
METHOD
There are 2 ways to submit a form. GET and POST.
GET ($_GET)
The GET method is used to submit the data into a URL encoded format. In our example if we set the method to GET the outcome result would submit the form to.
form_submit.php?form_field1_name=value&form_field2_name=value
etc.
POST ($_POST)
The POST method is the preferred way of processing a form. As unlike the GET method the data is not shown in the URL.
NAME The name variable is used so that the form can be referenced to from style sheets and scripts.
Now let’s add some fields to the form. In our case we will add 2 single line text boxes, one multi-line text box a drop down box and a submit button. Inside the form tags insert the following.
<input type="text" size="20" name="name" value="Full Name" /><br /> <input type="text" size="20" name="email_address" value="Email Address" /><br /> <textarea cols="30" rows="10" name="message">Contact Message</textarea><br /> <select size="1" name="subject"> <option>General Contact</option> <option>Technical Contact</option> </select><br /> <input type="submit" value="Submit Button" name="submit" /><br />
For more information on elements that can be used for form fields visit
http://www.w3.org/TR/html401/interact/forms.html#h-17.4
Once you have it all together save it as form.html. So far you should have the following.
<form action="form_submit.php" method="post" name="simple_form_design"> <input type="text" size="20" name="name" value="Full Name" /><br /> <input type="text" size="20" name="email_address" value="Email Address" /><br /> <textarea cols="30" rows="10" name="message">Contact Message</textarea><br /> <select size="1" name="subject"> <option>General Contact</option> <option>Technical Contact</option> </select><br /> <input type="submit" value="Submit Button" name="submit" /> </form>
This completes the HTML form section. Now if you upload form.html and visit the page it should look something like the image below.
So now we have got the form interface where the user can enter the data we need to create the page where the data entered is processed.
form_submit.php
This is in the file that we put in the action attribute (form_submit.php). So let’s start by setting some variables
$send_to_email = “your_email@website.com;
This is the email address to which the contact form will send the message to. Now we know where we are emailing the form data to we must retrieve the fields from the form.
$form_name = $_POST['name']; $form_email_address = $_POST['email_address']; $form_subject = $_POST['subject']; $form_message = $_POST['message'];
$_POST is an array which combines all the form fields. So we can access them using PHP. So for the sake of making it look prettier we will assign them to some more friendly names.
Once we have assigned the variables we need to actually check that the form has been submitted so that people can’t just visit form_submit.php directly and send a blank email. To check this we will look to see if the submit button has been passed over.
if ($_POST['submit'])
{
In this we are opening an if statement to see if $_POST[‘submit’] has a value which if you look back at the html form the value is Submit Button.
This next session goes though the $_POST array checking for any form fields that have been left blank using the function empty.
foreach ($_POST as $form_field_name => $form_field_value)
{
The foreach function is used to cycle through an array splitting the key and value into accessible strings
$_POST['KEY'] = VALUE;
In this case we are assigning the key to $form_field_name and the value of the array to $form_field_value. Next we will check to see if the value is empty.
if (empty($form_field_value))
{
Again we are using the empty function. Using this function empty is defined as being one of the following:
“” (an empty string)
0 (0 as an integer)
“0″ (0 as a string)
NULL
FALSE
array() (an empty array)
echo $form_field_name . " was left blank."; break 1;
In this bit if a form field has been found empty we will display the field name that was left blank and then add “ was left blank. Onto the echo after the form field name. The Break function escapes from loops such as the foreach we are running if an empty field is found. For more information on the break command visit http://www.php.net/break
} } $headers = "From: " . $form_name . " <" . $form_email_address . ">\r\n" . "X-Mailer: PHP/" . phpversion();
Now we have finished with sorting out the form fields lets start putting together the email. All email messages have headers, most are automatically created by the server but there are a few that we must include, who the email will be sent from and the type of message. The type of message in our case is sent via PHP we are including the version of php we are running as well using phpversion();.
On the first line we are creating the standard email address including the contact name such as,
Bill Anderson
So we are getting both the name and email address from the details submitted in the form and putting them in to create the format required.
Now for the final section where we actually use the mail function to send the email.
$send_mail = mail($send_to_email, $form_subject, $form_message, $headers); }
The mail format is (to, subject, message, headers(optional), additional_parameters(optional). So we are putting in all the variables we have created into the relevant locations. $send_to_email in the to section, $form_subject for the subject of the email message, $form_message for the message and finally $headers for the optional headers.
So that it in total the form_submit.php should look something like this.
<?php
$send_to_email = "your_email@website.com";
$form_name = $_POST['name'];
$form_email_address = $_POST['email_address'];
$form_subject = $_POST['subject'];
$form_message = $_POST['message'];
if ($_POST['submit'])
{
foreach ($_POST as $form_field_name => $form_field_value)
{
if (empty($form_field_value))
{
echo $form_field_name . " was left blank.";
break 1;
}
}
$headers = "From: " . $form_name . " <" . $form_email_address . ">\r\n" .
"X-Mailer: PHP/" . phpversion();
$send_mail = mail($send_to_email, $form_subject, $form_message, $headers);
}
?>
In the future I will be expanding on this tutorial to implement some safety features such as time restrictions between multiple submissions. Logging of IP addresses to help prevent spam and creating a CAPTCHA.
I hope you liked my tutorial, and if you need someplace to start messing around with PHP.





