PHP HTML Email Sender

Tired of the same old boring text newsletter? Well send your next out in HTML using this PHP script.

The Code

$theboundary = md5(uniqid(""));

$header = "From: \"$fromname\" <$fromemail>";
$header .= "\nMIME-Version: 1.0";
$header .= "\nContent-Type: multipart/alternative;";
$header .= "\n        boundary=\"----=_NextPart_$theboundary\"";
$header .= "\nX-Priority: 3";
$header .= "\nX-MSMail-Priority: Normal";

$htmlmessage = file_get_contents("htmlemail.html");
$textmessage = file_get_contents("htmlemail.txt");

$body = "This is a multi-part message in MIME format.\n\n";
$body = "------=_NextPart_$theboundary\nContent-Type: text/plain;\n\n";
$body .= $textmessage;
$body .= "\n------=_NextPart_$theboundary\nContent-Type: text/html;\n\n";
$body .= $htmlmessage;
$body .= "\n\n";

mail($to, $subject, $body, $header);

The Explaination
Line 2: Creates a string to be used as a boundary between different sections of the email.

Line 4: “From” Header
Line 5: MIME Version Header
Line 6: Header declaring multiple parts
Line 7: Header declaring part boundary
Line 8-9: Sets the email priority

Line 12: Gets the HTML version of email
Line 13: Gets the TEXT version of email

Line 15: Tells viewer its in multiple parts
Line 16: Begins TEXT part
Line 18: Begins HTML part

Sending HTML emails is very easy, once you know the format of sending one. Just remember to not overdo the HTML page, as it will increase bandwidth if you do a mass mail, and some people dont like big emails ;-)

PHP Image Sizes

You might need the size of an image for many reasons – in this tutorial I’ll go over the simple task of getting this information.

The Code

$info = getimagesize("image.gif");
$width = $info[0];
$height = $info[1];
$type = $info[2];
$attr = $info[3];

The function getimagesize returns an array with 4 values. I’ve written the above example so you can clearly see which indexes return which information – below you can see a shorter way of getting the same result.

list($width, $height, $type, $attr)
       = getimagesize("image.gif");

Using the Sizes
If you want to use the output to display an image, with the correct html width and height, you can do the following..

echo "<img src=\"image.gif\" width=\"$width\"".
     " height=\"$height\">";

Or if you want you can use the $attr which contains the html width & height code already:

echo "<img src=\"image.gif\" $attr>";

Uploading with PHP

There are all sorts of cool things you can do with a file upload script – upload banners for a banner rotator, upload avatars for a forum, upload zips for a download site, the list goes on.

You may not have realized it, but uploading in PHP is very easy. Here we’ll go over the two basic parts of uploading, the upload form, and the upload script.

Upload Form

<form enctype="multipart/form-data" action="upload.php" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
    <input type="hidden" name="action" value="submit">

This is your basic upload form. Some key things to point out: MAX_FILE_SIZE is what sets the max size. Note that if the PHP ini has a smaller max file size, the ini size is used. enctype If the data encoding type is not defined in this way, it just won’t work.

Upload Script

if ($action == "submit") {
$uploaddir = '/full/path/to/final/folder/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
   echo "Success: File uploaded.";
} else {
   echo "Error: File not uploaded.";

As you can see, PHP handles the uploading of the file automatically – it is just up to you to move the file from the temporary location to the final destination using move_uploaded_file.

PHP URL Rotator

With a URL Rotator you can advertise one URL, and spread the traffic over multiple sites. Or if you have a database of websites, you could make a “Random Site” link – a fun thing to use with blogs.

The Code

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

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

$query = "UPDATE `urls` SET `lasttime`='".time()."' WHERE `ID`='{$row["ID"]}'";
$result = mysql_query($query, $global_dbh);

Header("Location: {$row["URL"]}\n\n");

Database Requirements
In this example, you only need a table having two basic fields – ID, URL, and lasttime. The ID will make it easy to update the time, make sure that it is an auto-incrementing integer. lasttime is what we will use to make this a rotator, and not a random site. You simply pick the URL that has the smallest last time.

The Explaination
The first 3 lines should be easy to understand by now, if not you’ll want to read a basic PHP/MySQL tutorial.

Lines 5-7 select a url, but pick the URL with the smallest last time, which means it is the URL that hasn’t been viewed in the longest.

Lines 9-10 update the database with the current time for the URL choses. We use the ID, and not the URL, in case there are multiple entries for the same URL.

Line 12 is a simple redirection. Remember to keep the {}’s as those allow you to use the array inside the quotes.

Lines 13-14 simply end the script execution. This really isn’t needed with a standalone script, but remember that redirecting the user doesn’t stop execution of the script – and it could become an easy way to bypass a login script if you forget, so its always good to be in the habit of using exit() after a redirect, even when its a simple script.

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:

body {margin: 0; }

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:

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.