Friendly Dynamic Pages

You have probably noticed how all the articles here have nice looking addresses, and it isn’t some “script.php?id=4” page. Well in this tutorial I’m going to show you how I did it.

The first thing you are going to need to do, is come up with some type of naming scheme. For instance, all the articles are /articles/ID/keywords here. Then once you have that, you’ll also need the script which will be doing the dynamic part of all this.

What we will be doing, is just redirecting any requests that look like the naming scheme, and pull up the script instead of looking for the actual page. We do this by using the htaccess RewriteRule.

RewriteEngine on
RewriteRule ^articles/1\.html$ scripts/articles.php?id=1

The first thing to note: Before you can use the RewriteRule command in your .htaccess file, you need to use the RewriteEngine command. Otherwise you’ll get server errors.

This basic example shows us how the syntax works, and you can easily see what it is doing. Note that when you use the RewriteRule, the browser doesn’t know it at all. It is just telling the server “Hey, show them this page instead”.

Now if you want to have this dynamically allowed, you would need to use some regular expressions. Using the following code would allow any #.html article to be redirected:

RewriteRule ^articles/([0-9]+)\.html$ scripts/articles.php?id=$1

Just like in a normal regular expresion, you use the $1 symbol to put what was found in the parnthasis in its place. The reason we have 0-9 is so only numbers are used, and the + tells it to allow more than one. This will allow articles/99.html – but not articles/free.html

Now the numbers still don’t look to good for users. Search engines will like the .html extension, and no question mark gibberish. But users won’t be able to remember the article numbers of their favorites if they want to pick from their history. So thats why I have the keywords section on CLiX Network.

To do it, its simple:

RewriteRule ^articles/([0-9]+)/(.*)$ scripts/articles.php?id=$1

Here the added /(.*) allows for any characters, and it makes the url look like a directory structure. If you want to pass the keywords to the script like I do, below is the code:

RewriteRule ^articles/([0-9]+)/(.*)$ scripts/articles.php?id=$1&keywords=$2

Now why would I go and do that? Simply because the script will send a redirect to the browser if the keywords are incorrect. This will help if someone just changes the article number, and not the keywords. If they do that and like the article, they may confuse themselves.

So there you have it! Enjoy! (In case you were wondering, even if you do this you can still Cache and Compress your page with PHP. The reason is because the server knows its a php page, even though the browser thinks its a .html or directory)

Caching and Compressing your site

If you have a large, dynamic website that uses many SQL calls you may want to cache your pages. And while you are at it, you can compress the cache too!

To use this tutorial you’ll need to have the zlib extension.

htaccess command
php_value auto_prepend_file /home/path/cache_begin.php
php_value auto_append_file /home/path/cache_end.php

By inserting these commands into your .htaccess file, you are telling it to include cache_begin.php before the script, and cache_end.php after the script. These files will contain the cache code, so you can cache all the php pages on your site without having to modify them all.

cache_begin.php

What cache_begin does, is it first makes up a cache file name. This name is just the MD5 of the REQUEST_URI. The MD5 keeps a unique name, but also removes any slashes and such from the filename. Using the REQUEST_URI, if you have site.php?page=2, it will generate a different cache than site.php?page=1

It then takes that cache name, and sees if the file exists. If it does, it then checks if the last time it was modified within the expiration. If it wasn’t, or if the file didn’t exist, it runs the scripts and caches the output. If it was, it displays the cache file and exits.

@ob_start(‘ob_gzhandler’); is what buffers the output, and compresses it with Zlib. If you want to cache your pages, but don’t have zlib, you can just use @ob_start(); – however I’d recommend you ask your host to install it if you dont ;-)

Things to note – $time_c23 is in seconds (86400 = 24 hours), the _c23 in the variables mean nothing – they just prevent you from overwriting the values within your script.

cache_end.php

This script is only executed when the cache needs to be generated. It takes the output buffer and saves it to the cache file, and then outputs it to the browser.

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));
fwrite($fp,”$buf”);
zip_entry_close($zip_entry);
fclose($fp);
}
}
zip_close($zip);
}
?>[/code]
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.

<?php
session_start();
session_register('sessioncode');
$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>
<INPUT TYPE=TEXT NAME="submit" VALUE="Submit"></FORM>

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.

<?php
session_start();
session_register('sessioncode');
$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);
imagepng($im);
exit();
?>

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.

<?php
session_start();
session_register('sessioncode');
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
http://www.clixnetwork.com/2005/3/15_howdoexchangespreven.html
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!