PHP Banner Rotator

So you’ve worked hard on your website, and now you want to rotate banners on your website and generate some cash. It’s time for a PHP Banner Rotator!

This code sample assumes you have a table named “banners” with at least two fields “SiteURL” and “BannerURL”. Which, shouldn’t need explaination as to what they are.

The Code

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

$query = "SELECT * FROM `banners` ORDER BY RAND() LIMIT 1";
$result = mysql_query($query, $global_dbh);
$row = mysql_fetch_array($result);

echo "<A HREF=\"{$row["SiteURL"]}\" TARGET=\"_blank\"".
     " BORDER=\"0\">{$row["BannerURL"]}</A>";
?>

The Core
The core of the code is that SQL query:

$query = "SELECT * FROM `banners` ORDER BY RAND() LIMIT 1";

This uses the built in MySQL function RAND() to select one (LIMIT 1) random (ORDER BY RAND()) row from the table banners.

Including the Rotator
If you want to include a banner right inside a page, simply use an include statement:

<? include "rotator.php"; ?>

Including Remotely
The easiest way to include your banner rotator remotely is to include the rotator.php script by using and iframe. But first, you’ll want rotator.php to output an entire page, with all the basic parts of a page (,etc) Then put in the following style tag:

<STYLE>
body {margin: 0; }
</STYLE>

This will make sure only the banner is shown, and no whitespace. Next you’ll use the following iframe code:

<iframe width=’468′ height=60 scrolling=’no’ frameborder=’0′ framespacing=’0′ marginheight=’0′ marginwidth=’0′ border=’0′ hspace=’0′ vspace=’0′ align=’right’ src="rotator.php"></iframe>

PHP Cron Jobs with cPanel

Running PHP scripts automatically can have some big benefits. You can wait to have things get done when there is less traffic on your server, or you can ensure daily tasks get done on time.

cPanel Simple Cron
Even if you do not know anything about cron jobs, and have never run a cron job before – you can get started with the simple cron tool built into cPanel. The url for it is:

https://www.yoursite.com:2083/frontend/x/cron/simplecron.html?

A few things you’ll need is the path to php and the path to the script that you’ll be running. You will need the full path to do this. If your path to PHP differs then the one below, then change it – otherwise keep it as is. Don’t know the path? This is most likely correct for you, just keep an eye out to see if the script does indeed run.

The command to run:
/usr/local/bin/php -f /home/(username)/public_html/(scriptname).php

Next you’ll want to select an option from all the select boxes. Remember to select an option in each box. If you want something to run every day at 4AM, select Minute: 0; Hour: 4; Day: Every; Month: Every; Weekday: Every;

Click save and you are all set! You’ll get an email every time the cron job runs, but if you don’t want to get it – put :blackhole: into the output email field at the top.

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.