Unzip files with PHP

I’ve been looking everywhere on how to do this, and I’ve been noticing lots of searches to the site looking for this. So I finally figured out how to do it, and am puting my findings here for you.

The first thing you’ll need to do is make sure you have the ZZIPlib library installed. If you have WHM, goto the Apache Build page, and just build apache with the “Zip” checkbox checked. That simple.

So what I’ve done is created a script that unzips the file “zip.zip” to the folder “zip”. You should know that if the zip file contains folders, the code below will not create those folders, but this should be enough to get you going on your own.

Unzip File PHP Code
[code type=php]<?php
$zip = zip_open(“zip.zip”);
if ($zip) {
while ($zip_entry = zip_read($zip)) {
$fp = fopen(“zip/”.zip_entry_name($zip_entry), “w”);
if (zip_entry_open($zip, $zip_entry, “r”)) {
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
Zip files usually have more than one file inside them, so when you open a zip file you need to go through each file. That is what the zip_read and zip_entry_read functions are doing.

zip_read is getting all the info for each file, and zip_entry_read is getting the file contents from the info returned by zip_read.

zip_entry_name returns the path of the file within the zip. If the file is in a folder inside the zip, you’ll need to create the directory before trying to write the file.

So there you have it: How to unzip a zip archive with PHP!

PHP Image Code Verification

If you’ve got a website with a form of any type, a user can easily abuse this form with a program that submits the form repeatedly. Using the power of PHP you can have your form generate a unique image every time that the user has to enter the text into the form. Below I’ll explain how to do it.

Setting up the form page
The form, form processor, and image script all need to be able to access the root code number. This number will then be put through an encryption routine to create the code that must be entered. We will do this by creating a session variable, and assigning a random number to it. We will do this on the form page below.

$sessioncode = rand(12345, 99999);
<FORM METHOD=POST ACTION="processor.php">
Comment: <INPUT TYPE=TEXT NAME="comment"><BR>
Code: <INPUT TYPE=TEXT NAME="code"> <IMG SRC="image.php"><BR>

Generating the image
The image will be generated by encrypting the code with MD5 and a unique string for your form. It will also be cut off after 6 characters, and will be in all uppercase. The code is below.

$im = imagecreate(55, 15);
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
imagecolortransparent($im, $bg);
imagestring($im, 5, 0, 0, substr(strtoupper(md5("Mytext".$sessioncode)), 0,6), $textcolor);

Verifying the code
Verifying the code is simple. Just uppercase the input from the user, and verify it by the encrypted code again like below.

if (strtoupper($code) == substr(strtoupper(md5("Mytext".$sessioncode)), 0,6)) {
   echo "Good job";
} else {
   echo "Bad job entering the code";

So there you go. You can now generate a php verification image and check the code against the user’s typing. You can get more advanced by adding random pixels and lines to the image to make it difficult for programs to be able to extract the text from the image.

Redirecting with HTACCESS

Before CLiX Network was launched I had various articles and how tos on my other websites. Now because CLiX Network is your place to find information you want, I figured it would be smart to put all the articles in one place. But then what do I do with the other copies of the articles?

Well that is where this article comes in. I’m going to show you how I redirected all those other articles here with simple .htaccess files. I’ll also discuss some other cool things you can do with these redirects.

Why .htacccess?
Well with .htaccess it is easy, and you can set the redirects as permanent. I want search engines and crawlers to know that the page isn’t coming back ever, and to always consider the article on this site now and not the others.

Let’s do it
You’ll want to open up notepad and start getting all the URLs together. The syntax is simple:

Redirect permanent /oldpage.html http://mysite.com/newpage.html

When I made mine, I just copied and pasted “Redirect permanent ” a bunch of times into notepad, then one by one I copied the RELATIVE urls of the old articles, and put the full path of the new articles like so:

Redirect permanent /articles/2_How_do_Exchanges_prevent_cheating.php
Redirect permanent /articles/3_Google_Page_Rank_in_Plain_English.php http://www.clixnetwork.com/2005/3/13_googlepagerankinplai.html
Redirect permanent /articles/4_Windows_XP_Adware_Removal.php http://www.clixnetwork.com/2005/3/16_windowsxpadwareremov.html
Redirect permanent /articles/5_Install_PHP_Scripts_Yourself.php http://www.clixnetwork.com/2005/3/17_installphpscriptsyou.html

Other Options
If you just moved something temporarily, or you want to tell the engine that the page is no longer there and its not coming back so stop listing it in the results, you can do that too. Instead of permanent, you can use any of the following keywords:

permanent - the resource has moved permanently
temp - it has temporarily moved elsewhere
seeother - the resource has been replaced
gone - it has been permanently removed

Here are some examples:

Redirect temp /article2.html http://www.mysite.com/imrewritingthis.html
Redirect seeother /article3.html http://www.mystie.com/betterarticle.html
Redirect gone /realyold.html

As you can see you have some flexability here. So now that you know this, remember to add a .htaccess entry every time you move or delete a page. It takes time, but it will help search engines and crawlers know what is going on with your site.

Install PHP Scripts Yourself

Installing PHP scripts is a fairly simple task. All you need is an FTP program, and you are all set. Below I’ll go over how to install scripts using my favorite FTP program, AceFTP. You can download it at freeware.aceftp.com.

Unzip the Files
Before we begin, you’ll need to have the script you want to install (or upgrade files) on your computer. They typically come in a .zip or .gz file. If you need a program to unzip files, check out www.7-zip.org. Unzip the files to a seperate folder on your computer. I keep all my files in a folder called /Sites/Sitename.com/, this way they are all organized.

Read the Readme
Just about every script comes with a readme.txt file. They typically will have instructions on what files to upload and where, or they will give you a URL to goto for this information. If there is no readme file, don’t fret.. It should still be just as easy.

Upload the Files
To upload the files, first you’ll need to connect to your webserver. With AceFTP you can goto File->Connect and create a Site Profile, so your FTP info will be saved for future use. Then double click the profile icon to connect.

The files on the left side are your computer’s files, and the files on the right are your webserver files. Simply click your way to the folder you unzip the files to on the left side, and on the right side goto your web folder (usually public_html or www). Then drag the files you want to upload from the left to the right.

CHMODing Files
With unix servers each file has set permissions for who can read, write, and execute them. PHP scripts don’t need to be CHMODed, so you can leave them alone (unless otherwise instructed to in the readme). To change the permissions (or chmod) a file, just right click it in the list in the right, click properties, and enter the value under CHMOD value. There is an easy to see group of check boxes, so you can see what permissions the file has. You can also CTRL/SHIFT click mutliple files/folders and CHMOD them all at once.

Simply CHMOD any files specified in the readme file. If you run the scripts and get a Permission Denied error, CHMOD the file that is listed as trying to be opened. If that file doesn’t exsist, you can CHMOD the directory it is supposed to be in, or create a blank file and upload that, and CHMOD that.

Configure your scripts
Each script is different, but there will generally be directions in the readme. If not settings can usually be found in the scripts themselves (open the file with notepad, and upload after making any changes), an install script, or admin script. The CLiX Network typically has an admin.php script with a default password of “password”, or a config.php file with variables inside.

If your settings are defined inside a script, make sure you read the descriptions carefully (good programmers will have self-explainatory variable names anyways). PHP Variables are setup as follows:

$variable = value;

Note that text values are enclosed in quotes. Examples:
$password = "password";
$credits = .1;

Make sure you put quotes on both sides, and you end the line with a semicolon. Also, variable names always start with a $ and don’t have any spaces or special characters!

Thats It
See, not so bad! The first time you’ll do it slowly, but soon you’ll be just like the Pros!

Building a dynamic site – Part 2

Continuing from “Building a dynamic site Part 2”, this article will go over building the php script that will take your page from the database, and insert it into the template, and output it to the user.

If you forgot to make a template, go back now and create one. Below is the PHP code we will be using to make our dynamic site:

$global_dbh = mysql_connect("localhost","username","password");
mysql_select_db("mydatabasename", $global_dbh);

$query = "SELECT * FROM `pages` WHERE `PID`=’$id’";
$result = mysql_query($query, $global_dbh);
$row = mysql_fetch_array($result);

$file = file_get_contents("template.txt");

$file = str_replace("##TITLE##", $row["Title"], $file);
$file = str_replace("##BODY##", $row["Body"], $file);

echo $file;

This is simply the opening PHP tag. It tells the server that what follows is PHP.

$global_dbh = mysql_connect("localhost","username","password");

This creates a connection to the MySQL server, and assigns a handle to $global_dbh. Simply replace username and password with your username and password for MySQL.

mysql_select_db("mydatabasename", $global_dbh);

This tells MySQL which database you’ll be using. Change mydatabasename to your actual database name.

$query = "SELECT * FROM `pages` WHERE `PID`='$id'";

This is the MySQL query we are going to be using. When we access the script its going to be page.php?id=## – The number is the Page ID used in the database.

$result = mysql_query($query, $global_dbh);

This line actually runs the query on the MySQL server.

$row = mysql_fetch_array($result);

This line takes the table row that was selected in the previous line, and assigns it as an array to $row

$file = file_get_contents("template.txt");

This gets the contents of your template file.

$file = str_replace("##TITLE##", $row["Title"], $file);

This inserts the TITLE of the page where you put ##TITLE## in your template.

$file = str_replace("##BODY##", $row["Body"], $file);

This inserts the BODY of the page where you put ##BODY## in your template.

echo $file;

This outputs the results to the browser


This tells the server that the PHP code has ended.

This script is very simple, but you should be able to get the idea and add more rows to your database, and more variables into the template. Just keep adding more replace lines.

In “Building a dynamic site – Part 3” we will go over how to create an index page that links to all your pages in your database.

Building a dynamic site – Part 1

Just about every large website is backed by some kind of database. In this series I’ll go over how to build your very own website that is powered by PHP and MySQL.

First you’ll need to make sure you have the following:
– Text Editor (notepad)
– PHP4, MySQL database
– phpMyAdmin

When building a dynamic site, there are a few key differences from a static website. In a static website, when someone requests a page the server sends the file back. With a dynamic site the server first grabs the information from a database, and then sticks it into a template, and then sends the file back.

The best part of going dynamic is being able to make changes to a single template, and instantly all the pages are updated. The downside is that databases use more resources. However this shouldn’t stop you from going dynamic!

The first step is creating the actual database table. For simplicity sake we are going to store the title and body into a table, and have MySQL auto-assign a Page ID to each page.

CREATE TABLE `pages` (

Copy and paste the code above into phpMyAdmin’s SQL query text box. This will create the database table for our tutorial.

The next step will be creating a template for our dynamic site. Since we are going simple, we will go with a simple template too:


Notice the tags we inserted, ##TITLE##, and ##BODY##. These are our place holders for the data inside the database.

In a real life dynamic site, we would have tables, menus, and such with the ##BODY## tag being in the center table cell where all the content goes. Feel free to make yours more impressive than mine.

Name the template file “template.txt”.

In “Creating a dynamic site – Part 2” we’ll start building the PHP page that will display the final result. Until then, start creating some pages using phpMyAdmin. To do so, select the table ‘pages’ from the left menu, and click ‘Insert’ on the top of the right page.