Welcome, To Be Efficient


Saturday, September 10, 2011


P L T, Programming Logics and Techniques are necessary for every computer people, and the efficient knowledge of PLT makes them an efficient programmer. In this chapter I will discuss P L T using programming language C, which is the dominant language for the Embedded Development then the assembly language.
Learn programming is a lot similar to learning a language that people speak like English or German. The best way to learn a 'human' language is to start speaking, listening, and repeating, and then checking out the grammar to make the language efficient. The Similar Method can be applied to the language C, we need to start writing programs as quickly as possible. So in this chapter includes lots of sample that make you PLT and efficient. 
1.     First Program – The Good Morning Program
The Hello world program is the basic program that ever seen in lots of books. It is the best starting program. You can even print your name. We must need an Editor 
and compiler to run the program. The Code for the program:

// Good Morning Program
#include
#include
void main()
{
clrscr();
printf(“\nGood  Morning\n”);
getch();
}


Save this code into a file, and call the file goodmorning.c, then compile and run  it by

Turbo C Compiler
Compile       Alt+ F9 or from the menu  compile > compile
Run        Ctrl + F9 or from menu run > run


A C program consists of functions, variables, constants and operator etc. The functions specify the tasks to be performed by the program. The Good Morning Program has one function called main. This function tells your program where to start running.  Main functions are normally kept short and calls different functions to perform the necessary sub-tasks. All C codes must have a main function.
Also notice that C is case-sensitive. The commands have to be written like they are above. C also denotes the end of statement with a semi-colon. Brackets signify either to "{" begin a group of statements, or "}" end a group of statements. The // or /* comment */ designates a comment. Anything after two slashes the compiler ignores. The last part of the program you should notice is the #include. This simply includes a group of functions from the filename specified between then less than and greater than signs (<...>). The file above stdio.h contains a list of standard functions for C to use, the function the our above program uses is printf. Printf takes a string of characters between quotation marks, and outputs them to the screen.

Thursday, November 12, 2009

PHP Exception Handling

What is an Exception

With PHP 5 came a new object oriented way of dealing with errors.

Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.

This is what normally happens when an exception is triggered:

* The current code state is saved
* The code execution will switch to a predefined (custom) exception handler function
* Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code

We will show different error handling methods:

* Basic use of Exceptions
* Creating a custom exception handler
* Multiple exceptions
* Re-throwing an exception
* Setting a top level exception handler

Note: Exceptions should only be used with error conditions, and should not be used to jump to another place in the code at a specified point.

Basic Use of Exceptions

When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block.

If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message.

Lets try to throw an exception without catching it:
1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}

//trigger exception
checkNum(2);
?>

The code above will get an error like this:

Fatal error: Uncaught exception 'Exception'
with message 'Value must be 1 or below' in C:\webfolder\test.php:6
Stack trace: #0 C:\webfolder\test.php(12):
checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6


Try, throw and catch

To avoid the error from the example above, we need to create the proper code to handle an exception.

Proper exception code should include:

1. Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown"
2. Throw - This is how you trigger an exception. Each "throw" must have at least one "catch"
3. Catch - A "catch" block retrieves an exception and creates an object containing the exception information

Lets try to trigger an exception with valid code:
1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}

//trigger exception in a "try" block
try
{
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}

//catch exception
catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
?>

The code above will get an error like this:
Message: Value must be 1 or below

Example explained:

The code above throws an exception and catches it:

1. The checkNum() function is created. It checks if a number is greater than 1. If it is, an exception is thrown
2. The checkNum() function is called in a "try" block
3. The exception within the checkNum() function is thrown
4. The "catch" block retrives the exception and creates an object ($e) containing the exception information
5. The error message from the exception is echoed by calling $e->getMessage() from the exception object

However, one way to get around the "every throw must have a catch" rule is to set a top level exception handler to handle errors that slip through.

Sunday, November 8, 2009

Creating Membership System using PHP and MySQL


This article will help you to create a membership system for your website using PHP and MySQL. One of the most unique and handy features of PHP and MySQL is the ability to create a user based login system for your website. With this feature your website can grow far beyond what you expected it to. Your website can become a community and it can become very interactive, therefore bringing users back to your website for more action.

During this tutorial I will show you how do the following:

  • Collect information about the user during signup and store that information into MySQL
  • Generate a random password and encrypt it into the database
  • Validate the user's email address before they can login
  • Create a login system for the user to validate his/her information against the database
  • Create a lost password recovery tool
  • Basic Form handling with PHP
  • Some PHP Session basics
  • Use the Mail function to send the user an email
  • And much more!

Let's keep in mind that this is all psuedo code. It may or may not work on your system without some type of modifications. If you read this tutorial carefully, I am sure that you'll figure it out with minimal brain cells wasted. Also, I would like to point out that this tutorial is based upon PHP 4.1 and later with register_globals turned off. Are you ready? Let's move on to creating the database.

Create the Database Structure

Let's begin by creating a standard database structure for you to use. First, you may use phpMyAdmin or something that you are familiar with to create your databases. I use phpMyAdmin because it's fairly easy to use and I don't have to store any applications or use any command line stuff while on my computer. Simply create your own database and call it whatever you want. Inside that database, run this SQL statement.

CREATE TABLE users (
userid int(25) NOT NULL auto_increment,
first_name varchar(25) NOT NULL default '',
last_name varchar(25) NOT NULL default '',
email_address varchar(25) NOT NULL default '',
username varchar(25) NOT NULL default '',
password varchar(255) NOT NULL default '',
info text NOT NULL,
user_level enum('0','1','2','3') NOT NULL default '0',
signup_date datetime NOT NULL default '0000-00-00 00:00:00',
last_login datetime NOT NULL default '0000-00-00 00:00:00',
activated enum('0','1') NOT NULL default '0',
PRIMARY KEY (userid)
) TYPE=MyISAM COMMENT='Membership Information';

Before I continue, I must say this. You may or may not agree with my column types in this example above. That's ok, it's not your database so please refrain from complaining about it. There is nothing wrong with these column types that will stop it from working like we want it to. Yes, I have had people complain about my databases structures before.

Now that you have created your database and you are ready to move on, let's start on collecting information about the user.

User Signup - Collecting the Data

Now that we've created a database and we're ready to move on to collecting information about this database. The first thing you want to do is create an information collection form. You can do this simply by using your favorite html editor, in my case either by hand or using DreamweaverMX. Don't worry, I'll include an example form along with all of the scripts you need in the sourcecode file with this tutorial. You can download it on the last page of this tutorial.

Our input form will look something like this:

First Name

Last Name

Email Address

Desired Username

Information about you:

This will gather enough information about the user for our purpose. You can always add more fields to the scripts in this tutorial, so don't worry!

This form will post to a script called register.Php and will do a few things that are essential. We'll put some basic error checking with PHP. I am not including any special Error checking functions on this form because everyone likes to do error checking their own way. I'll basically be checking that the user entered the required fields of this form and if they didn't, we'll put an error message on the page that they post this form to.

Note: Personally, I like to keep HTML where it belongs. As much as possible, I'll try to save HTML files in a specific directory on my web server and include them where necessary. So, I've saved this form in an HTML file on my server and I'll include it in my register.php where the error checking goes.

Let's look at the script that this form will post.

User Signup - Error Checking & Creating the Membership

The form you seen on the last page will actually post to a script called register.php. This script is shown below:

<?
include 'db.php';
// Define post fields into simple variables
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email_address = $_POST['email_address'];
$username = $_POST['username'];
$info = $_POST['info'];
/* Let's strip some slashes in case the user entered
any escaped characters. */
$first_name = stripslashes($first_name);
$last_name = stripslashes($last_name);
$email_address = stripslashes($email_address);
$username = stripslashes($username);
$info = stripslashes($info);
/* Do some error checking on the form posted fields */
if((!$first_name) || (!$last_name) || (!$email_address) || (!$username)){
echo 'You did not submit the following required information! <br />';
if(!$first_name){
echo "First Name is a required field. Please enter it below.<br />";
}
if(!$last_name){
echo "Last Name is a required field. Please enter it below.<br />";
}
if(!$email_address){
echo "Email Address is a required field. Please enter it below.<br />";
}
if(!$username){
echo "Desired Username is a required field. Please enter it below.<br />";
}
include 'join_form.html'; // Show the form again!
/* End the error checking and if everything is ok, we'll move on to
creating the user account */
exit(); // if the error checking has failed, we'll exit the script!
}
/* Let's do some checking and ensure that the user's email address or username
does not exist in the database */
$sql_email_check = mysql_query("SELECT email_address FROM users
WHERE email_address='$email_address'");
$sql_username_check = mysql_query("SELECT username FROM users
WHERE username='$username'");
$email_check = mysql_num_rows($sql_email_check);
$username_check = mysql_num_rows($sql_username_check);
if(($email_check > 0) || ($username_check > 0)){
echo "Please fix the following errors: <br />";
if($email_check > 0){
echo "<strong>Your email address has already been used by another member
in our database. Please submit a different Email address!<br />";
unset($email_address);
}
if($username_check > 0){
echo "The username you have selected has already been used by another member
in our database. Please choose a different Username!<br />";
unset($username);
}
include 'join_form.html'; // Show the form again!
exit(); // exit the script so that we do not create this account!
}
/* Everything has passed both error checks that we have done.
It's time to create the account! */
/* Random Password generator.
We'll generate a random password for the
user and encrypt it, email it and then enter it into the db. */
function makeRandomPassword() {
$salt = "abchefghjkmnpqrstuvwxyz0123456789";
srand((double)microtime()*1000000);
$i = 0;
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($salt, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
$random_password = makeRandomPassword();
$db_password = md5($random_password);
// Enter info into the Database.
$info2 = htmlspecialchars($info);
$sql = mysql_query("INSERT INTO users (first_name, last_name,
email_address, username, password, info, signup_date)
VALUES('$first_name', '$last_name', '$email_address',
'$username', '$db_password', '$info2', now())")
or die (mysql_error());
if(!$sql){
echo 'There has been an error creating your account. Please contact the webmaster.';
} else {
$userid = mysql_insert_id();
// Let's mail the user!
$subject = "Your Membership at MyWebsite!";
$message = "Dear $first_name $last_name,
Thank you for registering at our website, http://www.mydomain.com!
You are two steps away from logging in and accessing our exclusive members area.
To activate your membership,
please click here: http://www.mydomain.com/activate.php?id=$userid&code=$db_password
Once you activate your memebership, you will be able to login
with the following information:
Username: $username
Password: $random_password
Thanks!
The Webmaster
This is an automated response, please do not reply!";
mail($email_address, $subject, $message,
"From: MyDomain Webmaster<admin@mydomain.com>\n
X-Mailer: PHP/" . phpversion());
echo 'Your membership information has been mailed to your email address!
Please check it and follow the directions!';
}
?>

Don't worry, we'll begin talking about this script and explaining what all of this does now.

Let's start at the beginning.

<?
include 'db.php';

This code simply includes a script that I wrote that includes my database connection on a mysql_pconnect function. The reason I put this here is so that I don't have to continuously write out the database information every time I need it. PHP's include functions work great and can really save you a lot of time from writing out code over and over again. The mysql_pconnect function allows you to establish a persistent connection with the database.

What is a persistent connection? It's basically a way to reuse MySQL threads over and over again without starting a new instance of MySQL to handle each connection. Let's say you were browsing my site and you started a MySQL thread and then you left the site for awhile. Then, I came in and started browsing the website. I could actually pick up your MySQL thread and start using it instead of starting a new thread. This dramatically reduces the MySQL load on your server.

An example of how to establish a MySQL Persistent connection can be found here. The db.php file is written off of the code example found in that link.

Ok.. we've got the database stuff figured out. Let's move on to the next section of the script.

// Define post fields into simple variables
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email_address = $_POST['email_address'];
$username = $_POST['username'];
$info = $_POST['info'];
/* Let's strip some slashes in case the user entered
any escaped characters. */
$first_name = stripslashes($first_name);
$last_name = stripslashes($last_name);
$email_address = stripslashes($email_address);
$username = stripslashes($username);
$info = stripslashes($info);

These first section of code block simply convert the register_globals fields to simple variables for use in this script. This is my preference and I prefer to do that instead of typing out the full string each time I need to use it. You'll see that it can save you alot of effort.

The second code block will strip the slashes out of the user's posted fields. It uses the stripslashes() function which removes the backslashes ( \ ) found before each ' and " that PHP automatically adds to the posted fields. We do this because we might need to display the information that the user posts in the form if we find any errors in the error checking code below.

/* Do some error checking on the form posted fields */
if((!$first_name) || (!$last_name) || (!$email_address) || (!$username)){
echo 'You did not submit the following required information! <br />';
if(!$first_name){
echo "First Name is a required field. Please enter it below.<br />";
}
if(!$last_name){
echo "Last Name is a required field. Please enter it below.<br />";
}
if(!$email_address){
echo "Email Address is a required field. Please enter it below.<br />";
}
if(!$username){
echo "Desired Username is a required field. Please enter it below.<br />";
}
include 'join_form.html'; // Show the form again!
/* End the error checking and if everything is ok, we'll move on to
creating the user account */
exit(); // if the error checking has failed, we'll exit the script!
}

The code block above is actually very simple. It may look intimidating if you aren't very familiar with PHP, but trust me it's not that difficult to figure out. All this does is checks that each of the variables have something inside them. If not, we'll tell the user that they posted an empty field and they need to fill this back in. I'll verbalize the first row for you:

"If you did not enter anything in the first name field or you did not enter anything in the last_name field or you did not enter anything in the email address field or you did not enter anything in the username filed, I'll give you this error"

I hope that makes sense, because that's the way you need to verbalize it in your head. Using the || which also stands for "OR" is called a Bitwise Operator and it can be used to evaluate strings for your scripts.

Here's something that I would like to add. There's several ways to check if a string is empty. I am aware of that! Here's a couple.

if(!isset($string); or if(empty($string);

Using the isset() function or empty() function are up to you. I just check the ! (not bitwise operator) and it works fine for me.

Ok, some more about the code block above. If you examine the structure of it, you'll see that we will only display the applicable error. Once the error has been displayed, we'll give the user the form again and we'll fill in the applicable fields that they have already filled in. We do this by adding a value="<? echo $variable; ?> to the form input tag in the html.

The next function we used in this code block is the exit() function. This function will output an error message if you tell it to, and then exit the script without further execution of the code below it. I've found this is much easier than using one log if else statement to check the entire script for validity. Keep in mind, if you use a global footer.php file, you'll probably want to include this above the exit() function call or the bottom of your website may be cut off.

Next we'll do some checking inisde the database to ensure that we don't create a duplicate entry:

/* Let's do some checking and ensure that the user's email address or username
does not exist in the database */
$sql_email_check = mysql_query("SELECT email_address FROM users WHERE email_address='$email_address'");
$sql_username_check = mysql_query("SELECT username FROM users WHERE username='$username'");
$email_check = mysql_num_rows($sql_email_check);
$username_check = mysql_num_rows($sql_username_check);
if(($email_check > 0) || ($username_check > 0)){
echo "Please fix the following errors: <br />";
if($email_check > 0){
echo "<strong>Your email address has already been used by another member
in our database. Please submit a different Email address!<br />";
unset($email_address);
}
if($username_check > 0){
echo "The username you have selected has already been used by another member
in our database. Please choose a different Username!<br />";
unset($username);
}
include 'join_form.html'; // Show the form again!
exit(); // exit the script so that we do not create this account!
}

The above code checks the information that the user submitted and ensures that the email address and the username do not exist in the database already. If it does, we'll present the user with the form and have them enter a different value. This code block uses the unset() function which will remove the string $email_address and $username from PHP and it will in turn empty the form fields for those areas. Next, we'll prevent the script from going any furhter with the exit() function.

We also used a PHP/MySQL function to do our error checking called mysql_num_rows This function returns the number of rows found in the mysql_query that validate the set of circumstances we gave the mysql_query() function. Based upon that number, we can run some if statements and execute a certain set of commands we want to. You may find this very useful in your future scripts, so keep it in mind!

Let's go ahead and talk about the next block of code:

/* Random Password generator.
http://www.phpfreaks.com/quickcode/Random_Password_Generator/56.php
We'll generate a random password for the
user and encrypt it, email it and then enter it into the db.
*/
function makeRandomPassword() {
$salt = "abchefghjkmnpqrstuvwxyz0123456789";
srand((double)microtime()*1000000);
$i = 0;
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($salt, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
$random_password = makeRandomPassword();
$db_password = md5($random_password);

This code uses a Random Password generator which creates a 7 character random password and then sends it to the user while encrypting it with the md5() hash function and stores it into the database along with the user's information.

This code block serves a few purposes. The first one being that we don't want to give the ability to create their own password right away. We want to validate this user in some way, so we'll prevent them from creating their own backdoor into our site. Then, we'll encrypt the password using the md5 function which is one way encryption. You won't be able to decrypt it yourself. The only way to validate the md5 from the database is to encrypt whatever you type in and then check to see if the two fields equal each other.

Next code block please :)

// Enter info into the Database.
$info2 = htmlspecialchars($info);
$sql = mysql_query("INSERT INTO users (first_name, last_name, email_address,
username, password, info, signup_date)
VALUES('$first_name', '$last_name', '$email_address',
'$username', '$db_password', '$info2', now())") or die (mysql_error());
if(!$sql){
echo 'There has been an error creating your account. Please contact the webmaster.';
} else {
$userid = mysql_insert_id();
// Let's mail the user!
$subject = "Your Membership at MyWebsite!";
$message = "Dear $first_name $last_name,
Thank you for registering at our website, http://www.mydomain.com!
You are two steps away from logging in and accessing our exclusive members area.
To activate your membership, please click here:
http://www.mydomain.com/activate.php?id=$userid&code=$db_password
Once you activate your memebership, you will be able to login with the following
information:
Username: $username
Password: $random_password
Thanks!
The Webmaster
This is an automated response, please do not reply!";
mail($email_address, $subject, $message,
"From: MyDomain Webmaster<admin@mydomain.com>\n
X-Mailer: PHP/" . phpversion());
echo 'Your membership information has been mailed to your email address!
Please check it and follow the directions!';
}
?>

The beautiful thing about developing advanced web applications is that you can make things look more complicated than they really are. The above code block simply inserts the user's information that they posted along with the random encrypted password that we generated into the database and then emails the user a special link.

A couple of the functions we used here are mysql_error() which is very useful in determining what went wrong with your MySQL query. It will return specific information from the MySQL server that will tell you what went wrong with your query. Another great PHP and MySQL function is mysql_insert_id() this function will tell you what the number was assigned to the row you just created by the auto_increment primary key, which is kind of important right now.

We've also just tapped on the mail() function of PHP. While this tutorial is not designed to teach you everything about each function we use, our use of this mail() function is to send an email to the person confirming their email address and giving them a link to validate themselves on our server. We'll cover the specifics of the validation later on. Here's an example of the email that will be sent to your users:


From: MyDomain Webmaster
To: you@email.com
Subject: Your Membership at MyWebsite!

Dear Eric Rosebrock,
Thank you for registering at our website, http://www.mydomain.com!

You are two steps away from logging in and accessing our exclusive members area.

To activate your membership, please click here: http://www.mydomain.com/activate.php?id=3&code=969f8a1a7247ec82769e837c2f853450

Once you activate your memebership, you will be able to login with the following information:
Username: myusername
Password: msxsag4h

Thanks!
The Webmaster

This is an automated response, please do not reply!


You may be wondering why I sent the user an email with the encrypted password as the $code variable in the query string. Well, as I said before it doesn't really matter because 1) md5 can't be decrypted (easily anyways) and 2) it gives me a method of validating the user in the next script. The user probably won't know what the hell that md5 junk is anyways. You may be wondering if I just comprimised my website. No, not really. You can always give the user a method of changing his/her password immediately after the first login if you are that worried about it. Besides, the user can't paste his encrypted password into the login form because the only thing that will happen is that mumbo jumbo will get encrypted again therefore invalidating his/her login. Trust me, it's safe.

Well, we've done it! If everything is working so far, which it is on my test server, we're ready to create the validation script. It only gets easier from here. That first script was pretty long and from here on it becomes a sinch to do.

Activating the Membership

This next step is to create a script that based upon the email we have sent the user with their information, we can activate the account by just calling the script. Here's the script below:

<?
/* Account activation script */
// Get database connection
include 'db.php';
// Create variables from URL.
$userid = $_REQUEST['id'];
$code = $_REQUEST['code'];
$sql = mysql_query("UPDATE users SET activated='1' WHERE userid='$userid' AND password='$code'");
$sql_doublecheck = mysql_query("SELECT * FROM users WHERE userid='$userid' AND password='$code' AND activated='1'");
$doublecheck = mysql_num_rows($sql_doublecheck);
if($doublecheck == 0){
echo "<strong><font color=red>Your account could not be activated!</font></strong>";
} elseif ($doublecheck > 0) {
echo "<strong>Your account has been activated!</strong> You may login below!<br />";
include 'login_form.html';
}
?>

We'll skip the first codeblock about the db.php because I explained it eariler to you. The codeblock we'll talk about first is where we break the variables up in the query string to individual variables for simple use.

// Create variables from URL.
$userid = $_REQUEST['id'];
$code = $_REQUEST['code'];

Let me take a moment for the n00bies out there and explain a query string. This is basically your script's file name Ëäµú followd by a ? (question mark) and then the variable name and it's value. Each string and it's value are seperated from another string and it's value with an & (AN) sign. For example, our query string is:

activate.php?id=(The user's id from the mysql_insert_id function)&code=(The user's encrypted pasword)

By using this query string, I broke the code up by treating it as a $_REQUEST variable found in the PHP Manual Predefined Variables section. If I were to post something from a form, I would have used the $_POST and etc..

So, I turned the query string into two variables, $userid and $code for my MySQL query.

$sql = mysql_query("UPDATE users SET activated='1' WHERE userid='$userid' AND password='$code'");

From this point, I pull a MySQL query and then change the "activated" column which was Enumerated with the settings of 0 and 1. 0 being not activated and 1 being activated. During this update query, I check the information by the user by two additional fields in the database, userid and the password field.

If all of these values are correct in the query string and they match a row in my database, the affected row will be changed to "activated=1" and the user can now login.

$sql_doublecheck = mysql_query("SELECT * FROM users WHERE userid='$userid' AND password='$code' AND activated='1'");
$doublecheck = mysql_num_rows($sql_doublecheck);
if($doublecheck == 0){
echo "<strong><font color=red>Your account could not be activated!</font></strong>";
} elseif ($doublecheck > 0) {
echo "<strong>Your account has been activated!</strong> You may login below!<br />";
include 'login_form.html';
}
?>

This may seem reduntant to some people, or the wrong way of going about it, but to me this is the most strict method of checking to see if the row was actually updated properly and then giving the user the success or failed message. After my initial query of changing the activated column to 1 if the query string information was correct, I pull an additional query to doublecheck that it has definately been changed. We've already talked about the functions used here in previous code blocks.

As you can see, if the update was successful, we've simply displayed a small message and given the user the ability to enter his/her username and password to post to the next script.

Once again, all of these files are included in the soucecode file at the end of this tutorial.

The Login Verification

In the form that we displayed with the username and password fields, we will be posting to a file called "checkuser.php". This file is what really handles alot of the user processing after they have already registered and activated their membership. Let's take a look at this script now.

<?
/* Check User Script */
session_start(); // Start Session
include 'db.php';
// Conver to simple variables
$username = $_POST['username'];
$password = $_POST['password'];
if((!$username) || (!$password)){
echo "Please enter ALL of the information! <br />";
include 'login_form.html';
exit();
}
// Convert password to md5 hash
$password = md5($password);
// check if the user info validates the db
$sql = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password' AND activated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_array($sql)){
foreach( $row AS $key => $val ){
$key = stripslashes( $val );
}
// Register some session variables!
session_register('first_name');
$_SESSION['first_name'] = $first_name;
session_register('last_name');
$_SESSION['last_name'] = $last_name;
session_register('email_address');
$_SESSION['email_address'] = $email_address;
session_register('special_user');
$_SESSION['user_level'] = $user_level;
mysql_query("UPDATE users SET last_login=now() WHERE userid='$userid'");
header("Location: login_success.php");
}
} else {
echo "You could not be logged in! Either the username and password do not match or you have not validated your membership!<br />
Please try again!<br />";
include 'login_form.html';
}
?>

Don't panic! It's not that bad either! Let's break it down now.

<?
/* Check User Script */
session_start(); // Start Session

Ahh.. sessions. My favorite! Here we started a PHP Session using session_start(). This is a very simple task but can go wrong very easily. You MUST (let me underline that and make it bold) MUST do this before anything is displayed to your web browser by the script you are starting a session with. If you don't do this, you'll start getting some ugly errors saying Headers already sent by.... blah blah. I can garuntee you that this is a problem and will mess your website up something ugly. Don't make me repeat that!

If you do not start the session at the top of each script you are wanting to use sessions on, you will not be able to use the session variables. I usually do this in a header.php file and call the header.php file at the top of each of my scripts along with the db.php and etc. You'll figure that out on your own.

// Convert to simple variables
$username = $_POST['username'];
$password = $_POST['password'];

Once again, this is my personal preference and I like to simplify my variables. You don't have to perform this step if you don't want to, just fix the code below.

if((!$username) || (!$password)){
echo "Please enter ALL of the information! <br />";
include 'login_form.html';
exit();
}

You would not believe how many people will actually click the submit button on a form without typing something in. I don't know if it's hereditary or just something fun to do. The above code is simply a check to see if they did such a thing and give them the login form without executing the rest of the script first. Knuckleheads!

// Convert password to md5 hash
$password = md5($password);

Remember all of that stuff I was saying about passwords earlier? Well, this snipplet right here takes the human readable password (the one we emailed to the user) and then converts it to the md5 hashed version of the same password so we can check it inside the database and ensure that they match each other below:

// check if the user info validates the db
$sql = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password' AND activated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_array($sql)){
foreach( $row AS $key => $val ){
$key = stripslashes( $val );
}

This is the MySQL select query that checks the username and password match the one inside the database. This code block also returns the number of rows affected by the query and if the number is greater than zero (meaning that we have found a match because it would return 1) it will build the information we need in the rest of the script. If the $login_check variable is equal to zero, we'll simply present the login form again.

There's also something about this code block that I would like to point out. There's a chunck of code that will pull the information from your database and strip the slashes out of it and create a variable for each column inside your database that matches the row. This is a handly little snip that can save you tons of time when you need to stripslashes() a bunch of variables. Here's that exact snipplet by itself:

while($row = mysql_fetch_array($sql)){
foreach( $row AS $key => $val ){
$key = stripslashes( $val );
}

Let's say that I had 3 columns in my table. The first column being "first_name", second being "last_name" and third being "user_level". With this snipplet, I have just created $first_name, $last_name, and $user_level that has no backslashes in it and also have the values of the columns in the database. Pretty sweet eh? Good, thank php_rox the next time you see him on IRC :)

Back to the topic, here's the next code block

// Register some session variables!
session_register('first_name');
$_SESSION['first_name'] = $first_name;
session_register('last_name');
$_SESSION['last_name'] = $last_name;
session_register('email_address');
$_SESSION['email_address'] = $email_address;
session_register('special_user');
$_SESSION['user_level'] = $user_level;

Ahh the mighty sessions again! This is very simple believe it or not. A lot of people have a really difficult time with sessions, but this script will hopefully show you how they work.

Let me take a moment to expalin sessions to those who don't understand them that well. I'm not expert but I may be able to give you the idea.

We are all pretty familiar with a cookie. It's a little text file that's stored on our computers that contain information about us and it's only readable by the website that the cookie was issued from (and our text editors).

It may contain such information such as our first name, email address or when our last visit was. Well, that's cool but guess what? Lately, web browser developers and other software developers have been making it very difficult for webmasters to set cookies anymore. The cookie reliability rate has dropped dramatically because of security levels and cookie blocking programs out there. PHP has fixed this for us.

A session is similar to a cookie, but instead of storing such information on the user's hard drive, it stores it on the server in a temporary directory instead. This cookie is assigned a special number and so is the session that the user has. If the session ID and the temporary file ID are the same, the webserver will access the session cookie on it's hard drive.

This gives webmasters alot of room to expand the functionality of their websites and it makes life easier becuase to my knowledge, the user can't block a session from being started. Oh, and when the user closes his web browser the temporary cookie is destroyed from the webserver. Got it? Hope so :)

The first thing we're going to do is create a session variable. We do this by registering a name to it:

session_register('first_name');

Then we assign that session variable name a value:

$_SESSION['first_name'] = $first_name;

So if the user's name was "Eric" our session value named "first_name" would become "Eric". In other words: $_SESSION['first_name']; would be "Eric" for this particular user!

The really cool thing about this is we can use this in many places on our website without querying the database anymore because we just registered it as a session. Just remember, each time we want to call a session variable, we MUST have session_start() at the top of that script.

Next please :)

mysql_query("UPDATE users SET last_login=now() WHERE userid='$userid'");
header("Location: login_success.php");
}


Alrighty, we've got a column in our database that we can use called "last_login" and it's of DATETIME column type. Since the user has been validated and everything is working as planned, we can now update the user's information and set the last_login column to a date that is equivalent to this very moment using the "now()" function.

You may be wondering why I chose to update the login_date on their membership. Well, later on let's say that our user database grows into the hundreds of thousands. Now my database is getting pretty large. I can create a script that can run every month to determine if a user has logged into the website sometime in the last 6 months. If they have, I'll leave their membership.

If they haven't I can delete their membership or even send them an email notifying them that I am about to delete their membership and therefore I change the activated value back to 0 and send them a link to reactivate it. If they don't activate it within 30 days, I'll delete it. This is completely optional, but it's a nice feature to build in. No, I won't show you how to do that :)

Ahh.. the header("Location: login_success.php"); Why did I do this? This is because I want to double check that the sessions have been stored properly. It's bascially the same thing as a Meta Refresh in HTML terms, execpt the PHP script will automatically direct you to the page in this header() function. Once again, just as session_start() this is one of "those" functions that must be called before any HTML is echoed to the user's browser.

Next block..

} else {
echo "You could not be logged in! Either the username and password do not match or you have not validated your membership!<br />
Please try again!<br />";
include 'login_form.html';
}
?>

Call this what you want it to, i.e: bad coding habbits or whatever, but I'll just say that this is the end of the error checking of the mysql_query. If no rows were found in the $login_check variable above, we'll simply give them this error and include the login form again.

Well, that's it for this script. We've either successfuly validated the user against the database and redirected them to our next script or we've given them a login form to try again.

Let's view last script for the login process.

Login Success Script

This script is the final phase of our login. If everything has gone well up to this point, we can show the user a success message that uses their session variables that we registered when they logged in. This script will also give you an introduction to user groups and access levels on your website.

Here's the script.

<?
session_start();
echo "Welcome ". $_SESSION['first_name'] ." ". $_SESSION['last_name'] ."!
You have made it to the members area!<br /><br />";
echo "Your user level is ". $_SESSION['user_level']." which enables
you access to the following areas: <br />";
if($_SESSION['user_level'] == 0){
echo "- Forums<br />- Chat Room<br />";
}
if($_SESSION['user_level'] == 1){
echo "- Forums<br />- Chat Room<br />- Moderator Area<br />";
}
echo "<br /><a href=logout.php>Logout</a>";
?>

Let's break it down!

<?
session_start();
echo "Welcome ". $_SESSION['first_name'] ." ". $_SESSION['last_name'] ."!
You have made it to the members area!<br /><br />";
echo "Your user level is ". $_SESSION['user_level']." which enables
you access to the following areas: <br />";

This starts the session as I have described in previous pages and then gives the user a welcome message with their first name, last name. It also precludes to which sections they have access to based upon the user_level setting in the database. See below.

if($_SESSION['user_level'] == 0){
echo "- Forums<br />- Chat Room<br />";
}
if($_SESSION['user_level'] == 1){
echo "- Forums<br />- Chat Room<br />- Moderator Area<br />";
}

Here we are checking the level that the user has access to and showing them the links. By now, this should be pretty easy to figure out. Basically "If your user_level = 0 you have access to Forums and Chat Room" or "If your user_level is 1 you have access to Forums, Chat Room and the Moderator Area".

echo "<br /><a href=logout.php>Logout</a>";
?>

This is the logout link to the next script.

The Logout Script

<?
session_start();
if(!isset($_REQUEST['logmeout'])){
echo "<center>Are you sure you want to logout?</center><br />";
echo "<center><a href=logout.php?logmeout=true>Yes</a> |
<a href=javascript:history.back()>No</a>";
} else {
session_destroy();
if(!session_is_registered('first_name')){
echo "<center><font color=red><strong>You are now logged
out!</strong></font></center><br />";
echo "<center><strong>Login:</strong></center><br />";
include 'login_form.html';
}
}
?>


Ok, I have finally used isset() variable. Here all I am doing is checking that the $logmeout variable is not set. If it isn't, I'll ask the user if they are sure they want to logout and give them two options.

The "Yes" option includes a query string back to the same script that has the $logmeout variable built inside of it and then passes the first if statement which destroys their session logging them out with the session_destroy() function and including the login form. They will no longer be logged in!

The only thing that I haven't covered is how to generate a lost password recovery tool. Let's do this and then I'll wrap up this tutorial so yot">n be on your way to making your website a community!

The Lost Password Utility

This is a vital tool for you to have because you won't be able to tell the users what their password is using the md5 encrypted passwords. Besides, emailing someone their password each time they need it would really suck. Let's keep it all automated!

Here's the script I would use:

<?
include 'db.php';
switch($_POST['recover']){
default:
include 'lost_pw.html';
break;
case "recover":
recover_pw($_POST['email_address']);
break;
}
function recover_pw($email_address){
if(!$email_address){
echo "You forgot to enter your Email address
<strong>Knucklehead</strong><br />";
include 'lost_pw.html';
exit();
}
// quick check to see if record exists
$sql_check = mysql_query("SELECT * FROM users WHERE email_address='$email_address'");
$sql_check_num = mysql_num_rows($sql_check);
if($sql_check_num == 0){
echo "No records found matching your email address<br />";
include 'lost_pw.html';
exit();
}
// Everything looks ok, generate password, update it and send it!
function makeRandomPassword() {
$salt = "abchefghjkmnpqrstuvwxyz0123456789";
srand((double)microtime()*1000000);
$i = 0;
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($salt, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
$random_password = makeRandomPassword();
$db_password = md5($random_password);
$sql = mysql_query("UPDATE users SET password='$db_password'
WHERE email_address='$email_address'");
$subject = "Your Password at MyWebsite!";
$message = "Hi, we have reset your password.
New Password: $random_password
http://www.mywebsite.com/login.php

Thanks!
The Webmaster
This is an automated response, please do not reply!";
mail($email_address, $subject, $message, "From: MyDomain Webmaster<admin@mydomain.com>\n

X-Mailer: PHP/" . phpversion());
echo "Your password has been sent! Please check your email!<br />";
include 'login_form.html';
}
?>

For this script, we created a lost_pw.html form which obtains the user's email address from their input. It also has a hidden field called "recover" with a value of "recover". At the top of this script I created a switch which is another method of validating information instead of using an if else statement.

We gathered the info, queried the database and found determined if we found a match. If we did, we sent the user's email a newly generated random password and updated the database with that information. Then we displayed the login form and told the user to check his/her email address for the new password.

If no email address match was found, we simply told the user and presented the lost password form again. If they didn't enter an email address, we called them a Knucklehead and told them to enter their email address in the form below.

Let's summarize on the next page.

Summary This has been quite a long tutorial. In it we have learned quite a few new things and hopefully you now have a better understanding of a login system, sessions, database queries and some of the functions we use every day in PHP. I have done my best to create a system that would be easy for you to understand and modify.

I hope you take it upon yourself to expand the features I have shown you in this tutorial. I highly recommend that you create a form that allows the user to change his/her information and modify their password to something they desire. I have researched login systems for quite awhile and I have also developed quite a few of them. To me, this is the most efficient method I have found to use.

I hope you enjoy it and thanks for reading!

Disclaimer

.........................................................................................................................................................
The all content are through my experiences, that i have learn in going through Studies and in building projects, some of were taken from some web sites, books and other sources, where i have visited and learn the concepts, I am very thankful to them for having those valuable things, which make me more efficient, and i have added those all in my experience. If any of these content violets copyrights, please contact me i will try to resolve and will do the needful assistance. Thank you all very much.
..........................................................................................................................................................
..........................................................................................................................................................
..........................................................................................................................................................