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

22Feb/100

Simple Solution for Php Includes – IFrames – Real Estate

Simple Solution for Php Includes - IFrames
Michael J Medeiros

I have recently created my first Php program. I wanted to share with others some of the problems that I encountered, and how I finally overcame these obstacles.
My Reason for needing a Php Include
To start, my most recent website features a free classified advertising solution, a modified version of PhpBB stripped to function as an Article Bulletin Board No replying, and a link directory. The business model of my Website offers free Classified Advertising, but charges a small fee for enhanced advertisements Featured, Bolded, and Better Placement. The Classifieds were purchased from a developer, so I had little experience with the application. The link directory was a free resource of an old program that I modernized a bit. I choose the old link directory because the links are clean. They are not replaced with coding to count outbound traffic. I figured this would increase the value of links, to sites who exchanged links with me.
To increase revenue on the new site, I realized that I needed to increase the value of,

18Feb/100

Developing State-enabled Applications With PHP – Web

Developing State-enabled Applications With PHP
John L

Installment 1
Developing State-enabled Applications With PHP
When a user is browsing through a website and is surfing from one web page to another, sometimes the website needs to remember the actions e.g. choices performed by the user. For example, in a website that sells DVDs, the user typically browses through a list of DVDs and selects individual DVDs for check out at the end of the shopping session. The website needs to remember which DVDs the user has selected because the selected items needs to be presented again to the user when the user checks out. In other words, the website needs to remember the State - i.e. the selected items - of the users browsing activities.
However, HTTP is a Stateless protocol and is ill-equipped to handle States. A standard HTML website basically provides information to the user and a series of links that simply directs the user to other related web pages. This Stateless nature of HTTP allows the website to be replicated across many servers for load balancing purposes. A major drawback is that while browsing from one page to another, the website does not remember the State of the browsing session. This make interactivity almost impossible.
In order to increase interactivity, the developer can use the session handling features of PHP to augment the features of HTTP in order to remember the State of the browsing session. The are basically 2 ways PHP does this:

Using cookies
Using Sessions

The next installment discusses how to manage sessions using cookies...
Installment 2
Cookies
Cookies are used to store State-information in the browser. Browsers are allowed to keep up to 20 cookies for each domain and the values stored in the cookie cannot exceed 4 KB. If more than 20 cookies are created by the website, only the latest 20 are stored. Cookies are only suitable in instances that do not require complex session communications and are not favoured by some developers because of privacy issues. Furthermore, some users disable support for cookies at their browsers.
The following is a typical server-browser sequence of events that occur when a cookie is used:

The server knows that it needs to remember the State of browsing session
The server creates a cookie and uses the Set-Cookie header field in the HTTP response to pass the cookie to the browser
The browser reads the cookie field in the HTTP response and stores the cookie
This cookie information is passed along future browser-server communications and can be used in the PHP scripts as a variable

PHP provides a function called setcookie to allow easy creation of cookies. The syntax for setcookie is:
int setcookiestring name, [string val], [int expiration_date], [string path], string domain, [int secure]
The parameters are:

name - this is a mandatory parameter and is used subsequently to identify the cookie
value - the value of the cookie - e.g. if the cookie is used to store the name of the user, the value parameter will store the actual name - e.g. John
expiration_date - the lifetime of the cookie. After this date, the cookie expires and is unusable
path - the path refers to the URL from which the cookie is valid and allowed
domain - the domain the created the cookie and is allowed to read the contents of the cookie
secure - specifies if the cookie can be sent only through a secure connection - e.g. SSL enable sessions

The following is an example that displays to the user how many times a specific web page has been displayed to the user. Copy the code below both the php and the html into a file with the .php extension and test it out.

[php
//check if the $count variable has been associated with the count cookie
if !isset$count {
$count = 0;
} else {
$count++;
}
setcookie"count", $count, time+600, "/", "", 0;
]

[html]
[head]
[title]Session Handling Using Cookies[/title]
[/head]
[body]
This page has been displayed: [=$count ] times.
[/body]
[/html]

The next installment discusses how to manage sessions using PHP session handling functions with cookies enabled...
Installment 3
PHP Session Handling - Cookies Enabled
Instead of storing session information at the browser through the use of cookies, the information can instead be stored at the server in session files. One session file is created and maintained for each user session. For example, if there are three concurrent users browsing the website, three session files will be created and maintained - one for each user. The session files are deleted if the session is explicitly closed by the PHP script or by a daemon garbage collection process provided by PHP. Good programming practice would call for sessions to be closed explicitly in the script.
The following is a typical server-browser sequence of events that occur when a PHP session handling is used:

The server knows that it needs to remember the State of browsing session
PHP generates a sssion ID and creates a session file to store future information as required by subsequent pages
A cookie is generated wih the session ID at the browser
This cookie that stores the session ID is transparently and automatically sent to the server for all subsequent requests to the server

The following PHP session-handling example accomplishes the same outcome as the previous cookie example. Copy the code below both the php and the html into a file with the .php extension and test it out.

[php
//starts a session
session_start;

//informs PHP that count information needs to be remembered in the session file
if !session_is_registered"count" {
session_register"count";
$count = 0;
}
else {
$count++;
}

$session_id = session_id;
]

[html]
[head]
[title]PHP Session Handling - Cookie-Enabled[/title]
[/head]
[body]
The current session id is: [=$session_id ]
This page has been displayed: [=$count ] times.
[/body]
[/html]

A summary of the functions that PHP provides for session handling are:

boolean start_session - initializes a session
string session_id[string id] - either returns the current session id or specify the session id to be used when the session is created
boolean session_registermixed name [, mixed ...] - registers variables to be stored in the session file. Each parameter passed in the function is a separate variable
boolean session_is_registeredstring variable_name - checks if a variable has been previously registered to be stored in the session file
session_unregisterstring varriable_name - unregisters a variable from the session file. Unregistered variables are no longer valid for reference in the session.
session_unset - unsets all session variables. It is important to note that all the variables remain registered.
boolean session_destroy - destroys the session. This is opposite of the start_session function.

The next installment discusses how to manage sessions using PHP session handling functions when cookies are disabled...
Installment 4
PHP Session Handling - Without Cookies
If cookies are disabled at the browser, the above example cannot work. This is because although the session file that stores all the variables is kept at the server, a cookie is still needed at the browser to store the session ID that is used to identify the session and its associated session file. The most common way around this would be to explicitly pass the session ID back to the server from the browser as a query parameter in the URL.
For example, the PHP script generates requests subsequent to the start_session call in the following format:
http://www.yourhost.com/yourphpfile.phpPHPSESSID=[actual session ID]
The following are excerpts that illustrate the discussion:
Manually building the URL:
$url = "http://www.yoursite.com/yourphppage.phpPHPSESSID=" . session_id;
[a href="[=$url ]"]Anchor Text[/a]

Building the URL using SID:
[a href="http://www.yoursite.com/yourphppage.php[=SID ]"]Anchor Text[/a]

About The Author

John L is the webmaster of http://www.bimmercenter.com..
daboss@bimmercenter.com