Wednesday, August 1, 2007

PHPMailer Helper Class Demystified

Hi, welcome to another episode of my programming tutorial here on Vic2x Programming Tutorials Portal. This is about the famous PHP class used commonly in most PHP mail applications. It's called PHPMailer, you can download the thing from http://phpmailer.sourceforge.net/

At first, upon looking at the manual on how to use PHPMailer class, I was telling myself, this will be another get-a-headache. But, sometimes, we just need to crack codes for our survival, the deadlines are always fast approaching. What I did, I studied the class on how to initialize its member variables and what member functions to call before sending a mail or set of emails. I noticed however, that by just doing the initialization and calling several member functions, would take some time to make unless you just copy-paste your previous work using the PHPMailer Class. I decided to make a helper class to do the tedious initializations and calling member functions just to send an email. Helper class for beginners' sake, are simply helper class! Just kidding. Ok, seriously, a helper class will simply make your life easier. Most of the time, you will only have small number of lines in your programs to call some complicated functions or classes, in our case, the PHPMailer. That means, if you need to have 15 lines of codes just to send an email using PHPMailer class, using a helper class will lessen the lines of codes. Ok, I know what you're talking, let me give you the listings:

Prerequisites:
  1. You must have downloaded the PHPMailer class. The filename is class.phpmailer.php
    Simply extract that file in the folder where the following PHP files reside. Mine, I copied all of them to my htdocs folder, which is the root of your PHP engine.
  2. Once again, the following PHP scripts below should be located in the same folder as your class.phpmailer.php
Listing 1. Name your this PHP file as, sender.php


<?php
require_once('xmail.php');
$myMailer = new XMail("Test Subjet", "yourEmail@domain.com", "Juan Dela Cruz");
$emailAdds = "joemarie.aliling@gmail.com,joemarie.aliling@gmail.com";
$emailBody = "<h1>This is a test message</h1>";
if($myMailer->send($emailAdds, $emailBody)){
echo 'Mail has been sent.';
}else{
echo 'Failed to send mail.';
}
?>


Listing 2. This is the helper class, the XMail class, name this as xmail.php


<?php
require_once 'class.phpmailer.php';
class XMail{
var $objMail;
function XMail($subj='',$frmEmail='',$frmName=''){
objMail = new PHPMailer(); //instantiate our PHPMailer object
$this->objMail->From = $frmEmail;
$this->objMail->FromName = $frmName;
$this->objMail->isMail(); //we'll use the php core mail function
$this->objMail->Subject = $subj;
$this->objMail->isHTML(true); //we'll be sending an HTML email format..
}
function send($mailID, $mailBody){
$this->objMail->Body = $mailBody;
$arr = explode(",", $mailID); //separate the comma separated emails..
foreach($arr as $key => $value){ //loop through all addresses..
$this->objMail->AddAddress($value,"Recipient"); //set the recepient's address..
if(!$this->objMail->send()) return false; //exit with failure..
}
return true;
}
}
?>


Sorry, I made the listings' font size smaller so as to make it fit on the page.

There you are.. Simply execute the sender.php on your browser. But take note, it must be run on a server with mail delivery engine so that you can test the real action of the code. The code is easy to understand, take a while to read it, I commented all that need to be explained. You can use the XMail class for single email address or multiple addresses recipients. Just use comma to separate each email address. The mailer used in the XMail is simply the PHP's mail function. You can also set that to SMTP based one. Just go to the site of PHPMailer and see the documents on how to use SMTP delivery with the PHPMailer. If you have questions on the code, drop me a comment here, alright!

The codes presented here are free to use, reverse-engineer and use them in your applications
I hope, I have given you some insights on how Helper Classes or functions can help your programming tasks easier. Well, well, well, there you have it, PHPMailer Helper Class Demystified!

I would like to acknowledge the PHPMailer Team, thanks for the source! More power to you all!

If you need some Web Scraping and Curl Tips using PHP, check this site, Web Scraping and Curl

-Author, Philippines

Tuesday, July 31, 2007

Programming Tutorial Portal Tip 1

Coding Conventions Tutorial

Naming Variables

Always use meaningful variables in your program. Don't use num1 if that variable represents the average result. Worst still you would use the variable x for this. In programming, always bear in mind that you are programming for yourself and at the same time for others to clearly read it. That's need later if you are working as a team. Use variable names like these,

ave - to represent the average or you can simply use the word average itself.
x, y - for x and y coordinates.
subTota l - for the temporary result of a particular addition.
i, j, k, l, cntr - are usually common in loops.
payPerView,studPerRoom - this is the professional style of naming variables..

You see? The variables speak for themselves! Seeing these variables, the programming could immediately surmise what's the use of that variable.

Another form used by professionals is to precede the variable name with the data type of that variable. Example:

char chrLetter -- we precede Letter with chr to mean it's a character.

char strName[20] -- as you can see? Name is a string, we simply put str to make it stand
-- that it's a string.
int nAge -- Age is usually an integer, we don't have 1.5 age right? and the commonly
-- used prefix is n or int will do

double dblLightYears -- for double numbers used dbl as your prefix

float fVolume -- usually f is being used to represent float



Comments

In order to make a program understandable, you should include some explanatory notes at key places in the program. Most programming languages have provisions for putting comments in your programs. I myself have witnessed to the idea of not having comments in my program. I wrote a program a long time ago and what's unique about it is my reaction when I saw my uncommented source code. My reaction is simply, wow! Who wrote this program? Ahmmm? I really forgot the algorithm I used on it and it made me think it's not mine. Therefore, to save your time banging your head figuring out what a particular line does, simply use comments.

Example:

distance = speed * time; //Computes the distance traveled.



Indenting

One signature of a beginner's program is the way the source was laid out. Typically you will see, everything seems sticking to the left part of the monitor. It's like that the instruction codes are very afraid to touch the right side of the screen. I don't know what are they afraid of. If your a beginner in programming, you better practice your habit of indenting your source code as much as possible. Here's a typical style I prefer to use, take note this can also be applied to any other languages:


int main(){
int nAge;
printf("Enter your age: ");
scanf("%d", &nAge);

if(nAge < style="font-weight: bold;">

Neat isn't it? You see the hierarchy? It would take sometime to make it habit though. If you want to have your style of indenting, just remember, be CONSISTENT every time.

That's all for now.. Till the next Tip!

Kinds of Program Errors

Ever wonder what are the common kinds of program errors and what do they mean?
Here's an explanation about them..

The compiler will catch certain kinds of mistakes and will write out an error message when it finds a mistake. It will detect what are called syntax errors since they are, by and large, violation of the syntax or simply the grammar of the programming language, like omitting the semicolon in C or C++.

If the compiler discovers that your program contains a syntax error, it will tell you where the error is likely to be and what kind of error it is likely to be. If the compiler says your program contains a syntax error, you can be confident that it does. However, the compiler may be incorrect about either the location or the nature of the error. It does of determining the location of an error, to within a line or two, than it does of determining the source of the error. This is because the compiler is guessing at what you meant to write down and can easily guess wrong. After all, the compiler cannot read your mind. Error messages subsequent to the first one have a higher likelihood of being incorrect with respect to either the location or the nature of the error. Again, this is because the compiler must guess your meaning. If the compiler's first guess was incorrect, this will affect its analysis of future mistakes, since the analysis will be based on a false assumption.

If your program contains something that is a direct violation of the syntax rules for your programming language, the compiler will give you an error message. However, sometimes the compiler will give you only a warning message, which indicates that you have done something that is not, technically speaking, a violation of the programming language syntax rules, but that is unusual enough to indicate a likely mistake. When you get a warning message, the compiler is saying, "Are you sure you mean this?" At this stage of your development, you should treat every warning as if it were an error until your instructor approves ignoring the warning.

There are certain kinds of errors that the computer system can detect only when a program is run. Appropriately enough, these are called run-time errors. Most computer systems will detect certain run-time errors and output an appropriate error message. Many run-time errors have to do with numeric calculations. For example, if the computer attempts to divide a number by zero, that is normally a run-time error.

If the compiler approved of your program and the program ran once with no run-time error messages, this does not guarantee that your program is correct. Remember, the compiler will only tell you if you wrote a syntactically correct program. It will not tell you whether the program does what you want it to do. Mistakes in the underlying algorithm or in translating the algorithm into the C++ language are called logic errors. Example of this is, instead of having the symbol + for your addition of two variables, you use * instead, which is for multiplication. This will simply yield an erroneous result. If the compiler approves of your program and there are no run-time errors, but the program does not perform properly, then undoubtedly your program contains a logic error. Logic errors are the hardest kind to diagnose, because the computer gives you no error messages to help find the error. It cannot reasonably be expected to give any error messages. For all the computer knows, you may have meant what you wrote.


TIP:

If you want to test your program for Logic Errors, you should try as much as possible, all representative data for your inputs and see their effect on your program. This way, in every generation of your testing, you will finally fine-tune your program and you'll become more confident with its execution. The only way to justify confidence in a program is to program carefully and so avoid most errors.

Monday, July 30, 2007

Programming Languages Short-Circuit

Have you heard about the thing as Short-Circuit in Programming? Sounds strange since it can be only applied to electrical concepts right? It is also considered as a fault in an electrical device. But the term is used often in programming languages way of evaluating logical expressions or conditional statements. Without an understanding about Short-Circuits in Programming languages, sometimes mysterious things do happen and you simply say that there's a bug in C! Also, without this knowledge about short-circuits in your program's logic could lead to a disaster. Programs crashing in the middle of it's execution. So, let's join hands and conquer the idea behind Short-Circuit in Programming Language

Here's a typical program written in C:

#include<stdio.h>
#include<conio.h>


int main(){
int i;
clrscr();
char str[8] = "monopono"; //assign our string with this text..
i = 0;
while((str[i] != 0x0) && (i < 8)){ //the 0x0 means null and is usually found
//after at the end of a string.
printf("%d %c ", i, str[i]); //simply output the variables values..
i++;
}
getch();
return 0;
}

ok, let's try to analyze this very complicated program. Let's jump directly to the looping statement, our while statement.. So this can read this way, Repeat the following statements WHILE i is less than 8 AND the current character being pointed to by i in our string str is not yet null or 0x0.. Are you with me? If you cannot understand it, read it again..

Considering the conditions given ,((str[i] != 0x0) && (i < 8)), our loop will simply iterate the statements inside if our i is less than 8 AND at the same time we haven't found a null character yet in our string.. Ok the crucial part is when the loop has iterated 8 times already. Can you guess what's the value of the variable i once the loop has finished? Hope you guessed it right, it's 8! If you don't agree with me, try it on..

So that's the danger, the value 8 itself! Take note we alloted 8 characters for our string right? And our C language starts counting from zero, especially in arrays such as our variable declaration of our string str[8] above. So that means the last character of our string should be referenced as str[7] since the first character is str[0], agree?

Ok back to the loop, let's assume that the loop has repeated 8 times already, so the current value for our i is 7, so replacing, the condition now looks like this,

((str[7] != 0x0) && (7 < 8))

still with me? So the condition for our loop is still true, the str[7] contains the character 'o' and IT IS NOT EQUAL to 0x0 right? And our variable i is still 7 which is still LESS THAN 8, so that means, we'll have another loop remaining and the loop will simply execute the statements inside including the last part the i++ and this time our variable i will have a value of 8 since it's been incremented by 1. Now is the moment of truth, variable i having a value of 8 and our next execution goes to our conditional statement,

((str[i] != 0x0) && (i < 8))

so replacing i with 8

((str[8] != 0x0) && (8 < 8))

That's the danger in every programming languages especially the C or C++ since there's no bound-checking being implemented.. So in this case our string str[8] is pointing to the 9th character which we have not defined in our variable declaration, that means we are accessing areas of memory which are not meant to be accessed by our program. In some case, repeatedly running your programs like this might crash your computer depending on the OS you're using. Mine before I was using Win 98 and I had terrible experiences about this error.

So what's the trick? That's where Short-Circuit comes in, you simply swap the two logical expressions like this,

((8 < 8) && (str[8] != 0x0))

Short-Circuit will save you from this undocumented error. Typically, programming languages evaluate logical expressions from left to right and once they find out that a single logical expression has become the traitor among other logical expressions, which means it's the only ONE which has not satisfied a certain condition, immediately the evaluation of other logical expressions will be postponed. In our case, once the (8 < 8) has been evaluated which has now become false, and since we are having the && operator which means every condition must be true for the our loop to stay alive, the program flow will immediately cut the evaluation of the remaining logical expression which is the (str[8] != 0x0) and the whole loop will come to an end finally.

I hope you have added this simple information to your plethora of programming theories. If you have questions on this post, kindly post a comment and I will really
and truly appreciate it.

Till the next stuff, see ya!

Sunday, July 29, 2007

Programming tutorials sites useful for beginners

Programmers Heaven

Planet Source Code

Game Development

PHP Net

PHP Tutorials

For sources of free e-books, I recommend going to this site:

Betah.co.il

Star Field Simulation Written in Turbo C

Ever wonder if you could create a starfield simulation like that of the screensaver of windows? Here's the program I wrote last 7 years ago. It's a Dos-based application so don't run it in Visual C++. I used Turbo C++ for Dos. If you want to run this, you can simply copy-paste the source code and you have to edit the comments since it's not really formatted here properly on this site. So don't blame me if you found a lot of errors.. Anyway, if you have question about this program, just post a comment here on this blog. Take note, the code presented here is quite advanced, so you may find some cryptic syntax around.. Don't be scared though, there are a lot of things you can learn from the code itself. So go ahead, and reverse-engineer it if you like.

By the way, you can press the arrow keys once it's already running and to exit the program, simply press Esc.

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <dos.h>

const Maxstars = 1056; //Determine the number of stars

const RIGHTARROW = 77; // {Right Coursr Key}
const LEFTARROW = 75; // {Left Coursr Key}
const UPARROW = 72; // {Up Coursr Key}
const DOWNARROW = 80; // {Down Coursr Key}
const ESCAPE = 1;

typedef unsigned char byte;


byte keystruck[128];

void interrupt (* oldInt9)(...); //oldInt9 is a pointer to an interrupt handlr

typedef unsigned char byte;
typedef struct star_id
{
int x ;
int y ;
int z ;
int speed ;
int color ;
} star_ID;

star_ID star[Maxstars] ;
int loop, Zoff ;
int Screen_X[Maxstars], Screen_Y[Maxstars] ;
int color, cntr ;


void interrupt newInt9(...)
{ //This is the new interrupt 9.
//It will determine if a key is being pressed or released;
byte key;
key = inp(0x60) % 128 ; //Get the byte at port 60h
//if the byte returned is < 128 then return TRUE else FALSE;
keystruck[key] = (inp(0x60) < 128);

asm pushf; //Push all flags

oldInt9(); //Call the old interrupt 9
//Move the Tail to HEAD to Empty the keyboard buffer
pokeb(0x40,0x1A,peekb(0x40,0x1C));
}

void WaitRetrace()
{
// { This waits for a vertical retrace to reduce snow on the screen }
byte signal;
signal = inp(0x3DA); //Get the status byte of the CRT
signal &= 8;
while(signal > 0) //Loop while signal is high
{
signal = inp(0x3DA);
signal &= 8;
}
signal = inp(0x3DA); //Get the status byte of the CRT
signal &= 8;
while(signal == 0) //Loop while signal is low
{
signal = inp(0x3DA);
signal &= 8;
}

}


void init()
{
oldInt9 = getvect(0x9);
setvect(0x9,newInt9);
}

void restore()
{
setvect(0x9,oldInt9);
}



void pal(byte color, byte R, byte G, byte B)
{ //Set the background(0) palette;
asm{
mov al, color
mov dx, 0x3c8
out dx, al
inc dx
mov al, R
out dx, al
mov al, G
out dx, al
mov al, B
out dx, al
}
}

void Putpixel (int X,int Y, byte Col)
/*{ This putpixel was originally written by Denthor of ASPHIXIA,
modified by me for maximum optimisation. This is faster than
the BGI's Putpixel}
This puts a pixel on the screen by writing directly to memory. }
Optimized by J.V.A. */
{
asm {

mov ax, 0xa000 // Load the memory segment address
mov es,ax // to es { 8 }
mov bx,X // Store X to bx { 8 }
mov dx,Y // Store Y to dx { 8 }
mov di,bx // Copy X to di { 2 }
mov bx, dx // Copy Y to bx { 2 }
shl dx, 8 // Multiply Y by 256 { 8 }
shl bx, 6 // Multiply temp.Y by 64 { 8 }
add dx, bx // Add both product to get Y*320 { 3 }
add di, dx // Final location(X+Y) { 3 }
mov al,Col // Store the color { 8 }
mov es:[di],al // Put the color on this address { 10 }
}
}

void dPutPixel(int x, int y, byte drawcolor) {
/*
_AH = 0x0C;
_AL = drawcolor;
_CX = x;
_DX = y;
_BX = 0x01;
geninterrupt (0x10);*/
asm{
mov ax, y
mov bx, x
mov cx, 640
mul cx
add bx, ax
adc dx, 0
mov ax, 0xa000
mov es, ax
push bx
mov bx, 1
mov ax, 0x4f05
int 0x10
pop bx
mov al, drawcolor
mov es:[bx], al
}

}




void SetMCGA()
{
asm{
mov ax, 0x013
int 0x10
}
}
void GoTextMode()
{
asm{
mov ax,0x3
int 0x10
}
}

void InitStars(int I)
{
int temp ;
byte sign ;

star[I].x = random(160)+1; // {Set the initial x of the star}
star[I].y = random(100)+1; // {Set the initial y of the star}
star[I].z = 256; // {Set the z to default, the depth}
star[I].speed = random(5) + 3; // {This is to adjust the speed of a star}
star[I].color = 0;
sign = random(2);
switch (sign) { // {Make some random stuff}
case 1 : star[I].x = -star[I].x; break;
case 2 : star[I].x = star[I].x; break;
}
sign = random(2);
switch (sign) {
case 1 : star[I].y = -star[I].y; break;
case 2 : star[I].y = star[I].y; break;
}
}

void InitStarsD(int K)
{
int temp ;
int sign ;

star[K].x = random(160)+1; // {Set the x of the star}
star[K].y = random(100)+1; // {Set the y of the star}
star[K].z = random(256) + 1; // {Set the z to default}
star[K].speed = random(5) + 3;// {This is to adjust the speed of a star}
star[K].color = BLACK; //Starting color of star is black
sign = random(2);
switch (sign) { // {Make some random stuff}
case 1 : star[K].x = -star[K].x; break;
case 2 : star[K].x = star[K].x; break;
}
sign = random(2);
switch (sign) {
case 1 : star[K].y = -star[K].y; break;
case 2 : star[K].y = star[K].y; break;
}
}


int main()
{
long viewx, viewy;
init();
SetMCGA();
randomize();
//Set the drawing palette of the stars
for (loop = 0;loop <= 255; loop++)
pal(loop,loop % 63,loop % 63,loop % 63);

for (loop = 0;loop < Maxstars;loop++)
InitStarsD(loop); //{ Initialize all stars }

viewx = 160;
viewy = 100;
while (!keystruck[ESCAPE])
{
for (loop = 0; loop < Maxstars; loop++)//Process each stars
{
//Convert the 3D coordinates to 2D coordinates;
Screen_X[loop] = ((star[loop].x * 256 / star[loop].z ) + viewx);
Screen_Y [loop] = ((star[loop].y * 256 / star[loop].z ) + viewy);

//Check of Stars are beyond the screen area, if not then draw them
if ((Screen_X[loop] > 1) && (Screen_X[loop] < 319) && (Screen_Y[loop] > 1)
&& (Screen_Y[loop] < 199))
{
Putpixel(Screen_X[loop],Screen_Y[loop],star[loop].color % 256);

}
//If stars are beyond the view, create new one
if (star[loop].z <= 8)
InitStars(loop); // Create new star

//Move the stars towards the viewer.
star[loop].z = star[loop].z - star[loop].speed;
//Change the palette;
star[loop].color = star[loop].color + 1;

}
if (keystruck[LEFTARROW])
viewx -= 3;
if (keystruck[RIGHTARROW])
viewx += 3;
if (keystruck[UPARROW])
viewy -= 3;
if (keystruck[DOWNARROW])
viewy += 3;


delay(30);
//Erase the stars after drawing them
for (loop = 0;loop < Maxstars; loop++)
{
Putpixel(Screen_X[loop],Screen_Y[loop],BLACK);
}
}
restore();
GoTextMode();
return 0;
}