PHP Email Verification

If you have any type of website where a user signs up and enters an email address, you must verify that this is in fact their email address. Otherwise, you could find yourself in trouble for emailing someone who didn’t want you to email them.

These code snippets are only a portion of what you’d need. Of course you’d need some sort of HTML forms, and database, but you should be able to figure out how they work together easy enough.

Send The Email

<?
if ($action == "submit") {
$code = "Secret Code $email here";
$good = substr(md5($code),8,5);
mail($email, "Your Verification Code",
     "Please click the following URL to verify your email:\n\n".
     "http://www.mysite.com/verify.php?v=$good&email=$email\n\n".
     "Thanks Again!","From: \"My Name\" <[email protected]>");
echo "We've sent an email to verify your account.".
     " Simply click the link and you're all set.";
exit();
}
?>

This piece of code creates a verification code ($good) from a 5 character chunk of an MD5 hash of a secret code ($code). Note that $code contains the email address to be verified. It then just sends a link to the user and says to click it.

The verify code

<?
$code = "Secret Code $email here";
$good = substr(md5($code),8,5);

if ($v != $good) {
    echo "The Verification Code is invalid. Please Try Again.";
    exit();
}

echo "Congratulations, You've been verified.";
?>

It is as simple as generating the same verification code from a secret code. Note that if register_globals is off, you’ll have to use $_GET[“email”] instead of $email.

Logging in with Sessions

Creating a basic password protected area can be such a usefull tool on your website, but learning how to use sessions effectively can be difficult. I hope that by the end of this tutorial you’ll know all you need to know to get your own password protected area up and running.

The login.php Code
The following code should be used to create the login.php file, which will be where users are sent to if they are not logged in correctly.

<?
session_start();
session_register("spassword");
if ($action == "login") {
    $spassword = $password;
    Header("Location: protected.php\n\n");
    exit();
}
?>
Please login below:
<FORM METHOD=POST ACTION="login.php">
<INPUT TYPE=HIDDEN NAME="action" VALUE="login">
<INPUT TYPE=PASSWORD NAME="password">
<INPUT TYPE=SUBMIT VALUE="Login"></FORM>

The code is pretty simple. Before you can use sessions you must turn session handling on, and register the variables you wish to use. session_register can handle multiple variables at a time, just put a comma in between them. Notice the variable names are without the $ and in quotes.

The next section checks if the user submitted the form by seeing if the hidden variable is set. If it is, it then sets the session variable to the inputted password. Note that if I didn’t do this, the session variable would still be blank even if the form used the same variable name.

It then redirects the user to the protected page, which will use the code below.

The protected.php Code
This page is the page you’ll want protected. All the content would go after the PHP code, and you could make multiple copies of this page to make multiple pages that require a login.

<?
$thepw = "SECRET";

session_start();
session_register("spassword");
if ($spassword != $thepw) {
    Header("Location: login.php\n\n");
    exit();
}
?>

This code is incredibly simple. It just turns sessions on again, registers spassword as the session variable (I use spassword so the s reminds me that it is in a session – not inputted by a form). It then checks if this variable holds the same text as the configured password ($thepw) and if not redirects to the login page.

Remember: It is important you use the exit(); function here to make PHP stop sending output after the location change. This is because users could setup their browser to not change location and view the page as it continues to be outputted.

Simply put your page below that PHP end tag. Whatever is there will only be visible if the user logged in with the correct password.

PHP Image Resizing

In this tutorial, I’ll quickly go over how to resize images with PHP. To do so is pretty simple: Open the image to be resized, create a new image of the new size, and copy the resampled image over.

The Code

<?php
header(‘Content-type: image/jpeg’);
list($w, $h) = getimagesize($filename);

$resized = imagecreatetruecolor($width, $height);
$original = imagecreatefromjpeg($filename);
imagecopyresampled($resized, $original, 0, 0, 0, 0, $width, $height, $w, $h);

imagejpeg($resized, null, 100);
?>

Usage
To use this script, you’d use it something like resize.php?filename=myphoto.jpg&width=120&height=75. Note that you’d want to do some sort of check on the input but for the sake of this tutorial this is fine.

Explanation
The first two lines are simple: You are telling the browser what to expect, and getting the width ($w) and height ($h) of the original image.

The next three lines are the core of what is going on. You are creating a new image with the new width and height, and opening the original image.

imagecopyresampled is then used. All the zeros are setting the top and left image pointers to the top left corner. If you want, you can resize a cropped section of the image by changing the second set of zeros. You can also put the resized image within a section of the new image by changing the first set of 0’s.

And of course the last 4 inputted values are the new sizes and old sizes. You could also change these if you want to crop or resize within an image.

We end it out by creating the jpeg image and outputting it to the browser.

PHP Image Distortion

In my article, PHP Image Code Verification, you may have noticed that it would be quite easy for a computer to read the code images, and enter the verification code automatically. In this article I will show you how to prevent this from happening by inserting random pixels to confuse the computers.

While this is not a 100% cheat proof concept, it can make it much more difficult to detect. If you are fighting comment spam, this could be the difference between 100 comments or 5. Chances are, if it will take a lot of CPU on their end to figure it out – they’ll go somewhere easier.

<?php
session_start();
session_register(‘sessioncode’);
$pixelnum = 20;
$width = 55;
$height = 15;
$im = imagecreate($width, $height);
$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);
for ($j=0; $j<$pixelnum; $j++) {
$color = ImageColorAllocate($image, rand(0,255), rand(0,255), rand(0,255));
imagesetpixel($image, rand(0,$width), rand(0,$height), $color);
}
imagepng($im);
exit();
?>

First some minor changes in the previous code. I’ve added a width and height variable, and the imagecreate function now uses those variables. This is because the pixels also need the height and width, so putting them into variables will make it easier to change later.

I’ve also added a new variable, $pixelnum, this will be the number of pixels to insert into the image. The more pixels, the harder for users to read and the harder for computers to read.

The main section of code that has been added is this:

for ($j=0; $j<$pixelnum; $j++) {
$color = ImageColorAllocate($image, rand(0,255), rand(0,255), rand(0,255));
imagesetpixel($image, rand(0,$width), rand(0,$height), $color);
}

This code loops through the number of times to insert a pixel, picks a random color, and picks a random spot to insert a pixel. If your image doesn’t have any other color than the code text, you may want to change that code to this:

for ($j=0; $j<$pixelnum; $j++) {
imagesetpixel($image, rand(0,$width), rand(0,$height), $textcolor);
}

This will be harder for users to read, but computers wouldn’t be able to just ignore non blue colors and read it plainly. You could also try having a random color for the text itself, which would make it increasingly difficult. Just remember, if you over-due it, your users may be very frustrated trying to view the images.

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.