DocuMAX The source for information

22Feb/100

Password Protection with PHP, MySQL, and Session Variables – Web

Password Protection with PHP, MySQL, and Session Variables
Dan McConkey

One of the great promises that actually came true when our Internet-enabled world reached the twenty-first century is efficient customer-to-business interaction. Each day, I find a new way to go through lifes errands without ever waiting on hold for a bank teller, a pharmacist, or an insurance agent. I do it all online.
Internet savvy consumers are coming to expect such web empowerment. And while these information transactions usually require some sort of private data traveling the ether, you, as the webmaster, bear the burden of keeping that data away from those who have no right to it.
Since retina scans and brain wave signatures are still properties of James Bond flicks, were stuck using plain old boring passwords.
Is this really secure
Lets get this out of the way first. The only truly secure computer is one thats unplugged. Kind of like "the only safe car is the one that sits in your garage." Life is a risk/reward proposition and, lets face it, this probably isnt Fort Knox, were securing.
The security measures listed here are suitable for garden-variety data. Ive used these schemes to write back-end website administration pages for online shopping carts. Ive used them to write "partner" pages where retailers can download ads and sales data from wholesalers. I wouldnt use them to secure credit card numbers, social security numbers, or nuclear launch codes.
So what are PHP, MySQL, and session variables
PHP is a programming language used in this case to write HTML. MySQL is a database. Session variable are used by web servers to track information from one page on a domain to another. This article isnt a how-to for either technology. If you arent very comfortable with them, you could just copy and paste the code samples in this article and build yourself a basic password protected website. You could also just read the Cliffs notes for Pride and Prejudice and get a C+ in literature class. Your choice.
Lets get started with sessions
Its often been said that the web is "stateless", meaning that each web page is entirely independent, needing no other page to exist, and taking no information from the previous page. This is great for anonymous surfing from one site to the next, but it stinks for password protection. Consumers want password protected information, but they dont want to enter their password on every page. So we turn to our web server to keep track of a user while hes on our site.
Ex. 1.
<php
session_start;
>
<!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Strict//EN http:// www.w3.org/ TR/ xhtml1/ DTD/ xhtml1-strict.dtd>
<html xmlns="http://www.w3.org/1999/xhtml"" xml:lang="en" lang="en">
<head><title>Dan McConkeys Free Web Marketing Guide</title></head>
<body>
<p>Dan McConkeys Free Web Marketing Guide</p>
</body>
</html>
end Ex. 1
session_start is a PHP function that looks to see if a session has already been started then does one of two things:
1. If a session has been started, it does nothing.
2. If a session has not been started, it begins one.
It is important to note that session_start must occur before any other PHP on the page, if you want it to work. Begin every password-protected page with it.
Validation
Now lets think basic validation. What sorts of things do we need to accomplish
* First, we need to check to see if the user has already logged in, so we dont ask for a password on every page. If our user has already logged in, we pass him or her through to the secure content.
* If the user hasnt already logged in, we need him or her to do so. So we need to write a log-in form.
* We need next to compare log-in form results with a known list of usernames and passwords. If the user checks out, we pass him or her along to the secure content.
* If the user doesnt check out, we direct him or her back to the log-in screen.
* Lastly, we need to provide the user the ability to log out.
So lets start with a basic frame-work that well fill in later.
Ex. 2
<php
// start session if not already started
session_start;
// check to see if user just logged out
if $log_out
{
}
function write_log_in $text
{
} // end write_log_in function
function verify
{
// check to see if theyre already logged in
// if yes, return true
// if no, check to see if visitor has just tried to log on
// if yes, verify password
// if it worked, return true
// if it didnt, send them back to log-in
// if the user didnt just log-in, she needs to
} // end verify function
>
<!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Strict//EN http:// www.w3.org/ TR/ xhtml1/ DTD/ xhtml1-strict.dtd>
<html xmlns="http://www.w3.org/1999/xhtml"" xml:lang="en" lang="en">
<head><title>Dan McConkeys Free Web Marketing Guide</title></head>
<body>
<p>Dan McConkeys Free Web Marketing Guide</p>
<php
// check for valid user
if verify
{
// begin secure content
echo "<p>Clatu, verata, nicto</p>";
// end secure content
} // end if verify
>
</body>
</html>
End Ex. 2
As I said, this is just a frame-work. I like to start all my projects this way. It allows me to get a grand view of what Im doing before getting mired down in the details.
Basically, so far, all weve done is place some secret content inside an if statement. If the user is valid, we show the content, if not, we dont.
Writing a log-in form
The first thing we should flesh out is our log-in function. This is a basic form, with no bells and whistles, so it should be pretty straight forward.
Ex 3
function write_log_in $text
{
echo "
<p>$text</p>
<form method=post action=>
<p>User ID: <input type=text name=user_name /></p>
<p>Password: <input type=password name=password /></p>
<p><input type=submit value=Log In></p>
</form>
";
} // end write_log_in function
End Ex. 3
No problems, right All this is is PHP writing a basic HTML log-in form. Two things are worth noting:
1. The method attribute to the <form> tag is post. We could have used get, but that would add our user name and password to the URL as varibles. ie our_urluser_name=bob&password=truck64 . This shows the password--in plain text-- right there in the URL. Why spend all this time on security if youre just going to put peoples passwords out for display
post is much more secure, forcing the server to keep track of form data, rather that the URL. Any time you can keep information out of the URL, youre one step closer to a secure web page.
2. Next you want to look at the action attribute to the <form> tag. Leaving it blank tells the server that you plan to process these form results with this same page.
Checking the log-in values
Now lets flesh out our frame-work a little more.
Ex. 4
<php
// start session if not already started
session_start;
// check to see if user just logged out
if $log_out
{
}
function write_log_in $text
{
} // end write_log_in function
function verify
{
// check to see if theyre already logged in
// if yes, return true
// check to see if visitor has just tried to log on
$user_name = $_POST["user_name"];
$password = $_POST["password"];
if $user_name && $password
{
// verify password and log in to database
$db = mysql_pconnect "localhost", "$user_name", "$password" ;
if $db
{
// register session variable and exit the verify function
$valid_user = $user_name;
$_SESSION[valid_user] = $valid_user;
return true;
}
else
{
// bad user and password
$text = "User Name and Password did not match";
write_log_in $text ;
}
}
else
{
// if the user didnt just log-in, she needs to
}
} // end verify function
>
<!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Strict//EN http:// www.w3.org/ TR/ xhtml1/ DTD/ xhtml1-strict.dtd>
<html xmlns="http://www.w3.org/1999/xhtml"" xml:lang="en" lang="en">
<head><title>Dan McConkeys Free Web Marketing Guide</title></head>
<body>
<p>Dan McConkeys Free Web Marketing Guide</p>
<php
// check for valid user
if verify
{
// begin secure content
echo "<p>Clatu, verata, nicto</p>";
// end secure content
} // end if verify
>
</body>
</html>
End Ex. 4
First, well check whether the user has just tried to log in.
$_POST is a PHP superglobal array that keeps track of data sent to a page via a <form method=post> tag. In the log-in function, we named our inputs user_name and password, so we can access the user input by calling $_POST["user_name"] and $_POST["password"].
We next run an if $user_name && $password statement to see if both $_POST["user_name"] and $_POST["password"] hold values. If they do, the user just tried to log in.
Our next section of code is the part that actually checks whether the user name and password are correct. Here, we use MySQLs User table part of the mysql database to keep track of our users. This is, perhaps, the best route, as MySQL is already set up to control access permissions. However, this can present problems when you want to keep the database connection open across pages. Also, some hosting companies wont give you grant access let you make new users to the mysql database.
In those cases, you can accomplish much the same thing by setting up your own users table in your database. You would then need to write an SQL query that compares user names and passwords. That would look something like this:
Ex. 5
$select = "select user_name from users
where user_name=$user_name
and password=PASSWORD $password ";
$query = mysql_query $select ;
if mysql_num_rows $query == 1
{
// validated user and password
...
End Ex 5
Getting back to our validation using MySQLs built in features, we know that the user name and password checked out because the connection attempt returned true.
Registering a session variable
Now that we know our user name and password check out, we need to store that information and allow our user to continue surfing our protected area without logging in each and every page. Looking back at example four, we notice another of PHPs superglobal variables: $_SESSION.
$_SESSION is an array that holds all of our session variables. By setting the valid_user session variable, we can later make a call to ession_is_registered "valid_user" to see if our user has already logged in successfully.
Logging out
The last thing we have to attend to is allowing our users to log out of our system. In this case, weve used a simple link inside our protected area.
Ex 6
<php
// start session if not already started
session_start;
// check to see if user just logged out
if $log_out
{
session_unregister "valid_user" ;
session_destroy;
session_start;
}
function write_log_in $text
{
} // end write_log_in function
function verify
{
} // end verify function
>
<!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Strict//EN http:// www.w3.org/ TR/ xhtml1/ DTD/ xhtml1-strict.dtd>
<html xmlns="http://www.w3.org/1999/xhtml"" xml:lang="en" lang="en">
<head><title>Dan McConkeys Free Web Marketing Guide</title></head>
<body>

<p>Dan McConkeys Free Web Marketing Guide</p>
<php
// check for valid user
if verify
{
echo "<p><a href=log_out=1>Log out</a></p>";
// begin secure content
echo "<p>Clatu, verata, nicto</p>";
...
End Ex 6
First, looking in the HTML body, we see a simple HTML link that adds a variable to the URL. In this case, the variable name is log_out and its value is 1. We use 1 as a value because its easy to store in a URL, but really any value greater than zero will work.
Once we pass a log-out request to the page, we need to process it. Thats what the if $log_out part is for.
The if statement checks if a log-out request was passed. Once it sees that one was, it unregisters the valid_user session variable, then it destroys the session entirely.
Ironically, it starts a new session right back up. Thats in case the user decides to log in later without closing the browser window, or log in as a different user.
The final code
Putting it all together we get this:
Ex. 7
<php
// start session if not already started
session_start;
// check to see if user just logged out
if $log_out
{
session_unregister "valid_user" ;
session_destroy;
session_start;
}
function write_log_in $text
{
echo "
<p>$text</p>
<form method=post action=>
<p>User ID: <input type=text name=user_name /></p>
<p>Password: <input type=password name=password /></p>
<p><input type=submit value=Log In></p>
</form>
";
} // end write_log_in function
function verify
{
// check to see if theyre already logged in
if session_is_registered "valid_user" return true;
// check to see if visitor has just tried to log on
$user_name = $_POST["user_name"];
$password = $_POST["password"];
if $user_name && $password
{
// verify password and log in to database
$db = mysql_pconnect "localhost", "$user_name", "$password" ;
if $db
{
// register session variable and exit the verify function
$valid_user = $user_name;
$_SESSION[valid_user] = $valid_user;
return true;
}
else
{
// bad user and password
$text = "User Name and Password did not match";
write_log_in $text ;
}
}
else
{
// user must log in
$text = "This is a secure server. Please log in.";
write_log_in $text ;
}
} // end verify function
>
<!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Strict//EN http:// www.w3.org/ TR/ xhtml1/ DTD/ xhtml1-strict.dtd>
<html xmlns="http://www.w3.org/1999/xhtml"" xml:lang="en" lang="en">
<head><title>Dan McConkeys Free Web Marketing Guide</title></head>
<body>
<p>Dan McConkeys Free Web Marketing Guide</p>
<php
// check for valid user
if verify
{
echo "<p><a href=log_out=1>Log out</a></p>";
// begin secure content
echo "<p>Clatu, verata, nicto</p>";
// end secure content
} // end if verify
>
</body>
</html>
End Ex. 7
Thats a pretty hefty code block to put at the head of every web page. Typically, I would put my verify and write_log_infunctions into a seperate file and reference them with an include function. That provides the added benifit of updating your entire website by editing one file only.
Hope that helps.
Copyright C 2005 Dan McConkey

About The Author

Dan McConkey is a freelance web marketing professional, working in and around Charlotte, NC. In the web, Dan has found an amazing potential for lead generation for businesses. Using traditional advertising theories, appropriate technologies, and a little common sense, your electronic marketing campaigns can easily be your most effective.
Dan maintains Dan McConkeys Free Web Marketing Guide at http://www.dmcconkey.com
dmcconkey@yahoo.com

16Feb/100

How To Manage Your Username And Password The Easy And Secure Way – Spyware

How To Manage Your Username And Password The Easy And Secure Way
Jerry Yu

Have been an Internet user for more than 9 years, I have 100s of logins and passwords to keep. Im paranoid. Im now even more paranoid after I joined YMMSS because I use online payment systems on weekly basis if not daily.
I used to use Microsoft Excel to manage my usernames, passwords, and other registration information, both online and offline. Excel is not safe because there are programs to crack password protected Excel workbooks and I even cracked the spreadsheet and VBA source code password for one of my old Excel financial models I developed. Today I still use Excel to store some personal information but I only save the Excel file on my another PC that is not connected to Internet.
In my article "6 Essential Steps to Protect Your Computer On the Internet", I highly recommended the award winning RoboForm. Free version of RoboForm http://www.roboform.com does come with limitations such as 10 Passcards only. If you dont want to buy the Pro version costs $29.99 as of my writing, there is an easy-to-use freeware see below you can download right now and manage unlimited usernames and passwords.
Download freeware Password Safe from SourceForge.net - the Open Source community.

https://sourceforge.net/projects/passwordsafe/

Here are some great features of Password Safe:

No installation is required. Simply download and double click the pwsafe.exe file.
Easy portable. Just copy and paste the EXE file and .dat database file to any disks. Be aware that when you open Password Safe in the other disk, you need to specify the database file location the .dat file.
One master password unlocks an entire password database that can contain all your other passwords.
Grouping. Usernames and passwords can be grouped into different categories you define, eg. Email Address, Payment, etc. You are in total control.
Strong, random password generation.
Copy username and password to clipboard so that you dont have to type them. Always keep in mind that you should never type any username and password.
Browse to URL. With one click, the URL related to your username and password can be opened in your default web browser. Another save on typing.
You can create more than one password database but you have to memorize more than one master password. Not recommended.

Here are some tips of using Password Safe version 2.04 and managing password in general.
Tip #1 - Always create a strong master password Safe Combination as used in the software.
Strong password should meet the following criteria:

At least 8 characters long to prevent cracking. The longer the better.
The password should contain lowercase, uppercase, numeric, and any other characters that are available on keyboard.
Ideally you should not use any meaningful words or numbers in the password. Totally random password is the best.

Tip #2 - Let PasswordSafe generate random password for you.
To generate random password:

Click the menu item Edit.
Select Add Entry or use corresponding icon button.
When the dialogue window opens, on the right hand side, you can see a Random Password Generate button. Click it, a random password will be automatically inserted in the Password field.

The generated random password is constructed according to the password policy defined in Password Safe. You can modify the default policy.

Click the menu item Manage.
In the dropdown menu, click Options.
Click the Password Policy tab.
Change the policy based on the strong password criteria stated above.

Some sites only allow alphanumeric passwords so make sure you select the appropriate check boxes when this is the case.
Tip #3 - Very Important: Never type your master password when open PasswordSafe.
Keylogger spyware can record keystrokes.
How can you enter master password without typing I do this.
Step 1: Open a Notepad file .txt.
Step 2: Copy and paste an article from any Internet website to this .txt file.
Step 3: Select characters from this article and copy, paste to form your master password.
Tip #4 - Very Important: Never lose your master password.
I memorize my master password. In addition, I also physically write it down to a hand written study material that has my previous uni works. Among the 1,000s of words, I placed my 22 characters master password in two different pages in encrypted format that can let me derive my master password.
Tip #5 - Categorize username and password.
When you add a new entry, you need to specify Group, Title, Username, Password, and Notes. The entries that share the same Group name will be gathered together automatically.
One Group can contain another Group as its sub Group. For example, I have Email Address group which contains three sub-groups as Friend, Work, Family.
Tip #6 - For security reasons, always use Copy Username to Clipboard and Copy Password to Clipboard.
Remember, never type username and password on a web form. This is how to do it.

Highlight an entry.
Right click mouse.
In the pop-up menu, select Copy Username to Clipboard or Copy Password to Clipboard
Go to your login form, paste the username or password.

You can use mouse to do copy and paste. If you prefer short-cut keys, this is how.
Copy: Ctrl+C Paste: Ctrl+V
Tip #7 - Use "Browse to URL" rather than typing URL in browser address bar.
When you enter a new entry or edit an existing one, you can enter a URL must start with http:// in the Notes field. You can save website login pages URL in this field. When you need to open a login page in browser, right click the entry and click Browse to URL in the pop-up menu. Then the login page will be opened in your default web browser automatically.
Tip #8 - Dont forget to backup your password database file.
Use the Make Backup menu item to save a second copy of your password file.
Tip #9 - Store your backups in a different offline computer or location.
This is a widely used backup strategy.
If you dont have two computers, you need to use other storage media to save a second copy of your backup file and version them by date easy to track back. Other storage media can be zip drive, thumb drive, floppy disk, CD, etc.
Off site backups are also important. Dont overlook this. You lose all your data if you lose both your computer and your other storage media all together for any reason.
Many companies provide online storage services for a fee. You can store any digital files you should password protect these files first on their secure servers. Search Google and you will find a lot.
I have two computers. One is used to surf net and it does not have any sensitive info stored on it. Another one is for my development work not connected to Internet and it has my backup files. I also store my backups in a thumb drive and CDs sometimes.

About The Author

The author, Jerry Yu, is an experienced internet marketer and web developer. Visit his site http://www.WebActionGuide.com for FREE "how-to" step-by-step action guide, tips, knowledge base articles, and more.