Home arrow MySQL arrow Page 4 - PHP, MySQL and Authentication 101
MYSQL

PHP, MySQL and Authentication 101


Authentication is required by any online admin system. In this article, Havard introduces us to two types of PHP/MySQL authentication: dialogs and forms.

Author Info:
By: Havard Lindset
Rating: 4 stars4 stars4 stars4 stars4 stars / 92
July 07, 2002
TABLE OF CONTENTS:
  1. · PHP, MySQL and Authentication 101
  2. · Authentication 101
  3. · HTTP Authentication (contd.)
  4. · Form Authentication
  5. · Conclusion

print this article
SEARCH DEVARTICLES

PHP, MySQL and Authentication 101 - Form Authentication
(Page 4 of 5 )

If you would like a more aesthetic approach to authentication, you may want to allow the user to log in using a HTML form. This is probably the most popular approach. We will be using sessions, so the user doesn't have to re-authenticate on every page that requires authentication.

Put the following code in a file called login.php:

<?PHP

$db = mysql_connect('localhost', 'dbuser', 'dbpass') or die("Couldn't connect to the database.");
mysql_select_db('dbname') or die("Couldn't select the database");

// Add slashes to the username, and make a md5 checksum of the password.
$_POST['user'] = addslashes($_POST['user']);
$_POST['pass'] = md5($_POST['pass']);

$result = mysql_query("SELECT count(id) FROM users WHERE password='$_POST[pass]' AND username='$_POST[user]'") or die("Couldn't query the user-database.");
$num = mysql_result($result, 0);

if (!$num) {

// When the query didn't return anything,
// display the login form.

echo "<h3>User Login</h3>
<form action='$_SERVER[PHP_SELF]' method='post'>
Username: <input type='text' name='user'><br>
Password: <input type='password' name='pass'><br><br>
<input type='submit' value='Login'>
</form>";

} else {

// Start the login session
session_start();

// We've already added slashes and MD5'd the password
$_SESSION['user'] = $_POST['user'];
$_SESSION['pass'] = $_POST['pass'];

// All output text below this line will be displayed
// to the users that are authenticated. Since no text
// has been output yet, you could also use redirect
// the user to the next page using the header() function.
// header('Location: page2.php');

echo "<h1>Congratulations</h1>";
echo "You're now logged in. Try visiting <a href='page2.php'>Page 2</a>.";

}

?>


Let's take a closer look at some parts of the code:

$db = mysql_connect('localhost', 'dbuser', 'dbpass') or die("Couldn't connect to the database.");
mysql_select_db('dbname') or die("Couldn't select the database");

// Add slashes to the username, and make a md5 checksum of the password.
$_POST['user'] = addslashes($_POST['user']);
$_POST['pass'] = md5($_POST['pass']);

$result = mysql_query("SELECT count(id) FROM users WHERE password='$_POST[pass]' AND username='$_POST[user]'") or die("Couldn't query the user-database.");
$num = mysql_result($result, 0);

if (!$num) {

// When the query didn't return anything,
// display the login form.

echo "<h3>User Login</h3>
<form action='$_SERVER[PHP_SELF]' method='post'>
Username: <input type='text' name='user'><br>
Password: <input type='password' name='pass'><br><br>
<input type='submit' value='Login'>
</form>";


This code connects to the database, and prepares the variables for the SQL query. After the data is prepared, we're querying the database for the information entered in the form. If the query doesn't return anything, we display the login form. Instead of hard coding the form, you could also make the form a .html file, and just include() it.

} else {

// Start the login session
session_start();

// We've already added slashes and MD5'd the password
$_SESSION['user'] = $_POST['user'];
$_SESSION['pass'] = $_POST['pass'];

// All output text below this line will be displayed
// to the users that are authenticated.

echo "<h1>Congratulations</h1>";
echo "You're now logged in. Try visiting <a href='page2.php'>Page 2</a>.";

}


This part gets executed when the information entered matched a user. We're starting a session through using the session_start() function, and then we're adding the session variables $_SESSION['user'] and $_SESSION['pass']. Since we've already added the slashes, and made the password an MD5 checksum, we'll just add them as they are. By the way, since we're using sessions, the login information will be deleted when you exit your browser. You may implement a normal cookie here too, so that it stays on your machine until it either expires, or the user deletes it manually.

Since there hasn't been any output anything to the browser just yet, we can redirect the user using header() redirection instead of displaying text. Just replace the text with this: header('Location: page2.php');

Now it's time to take a look at page2.php, which we linked to from login.php. Insert the following code into a file called page2.php:

<?PHP

// Start the login session
session_start();

if (!$_SESSION['user'] || !$_SESSION['pass']) {

// What to do if the user hasn't logged in
// We'll just redirect them to the login page.
header('Location: login.php');
die();

} else {

// If the session variables exist, check to see
// if the user has access.

$db = mysql_connect('localhost', 'dbuser', 'dbpass') or die("Couldn't connect to the database.");
mysql_select_db('dbname') or die("Couldn't select the database");

$result = mysql_query("SELECT count(id) FROM users WHERE password='$_SESSION[pass]' AND username='$_SESSION[user]'") or die("Couldn't query the user-database.");
$num = mysql_result($result, 0);

if (!$num) {
// If the credentials didn't match,
// redirect the user to the login screen.
header('Location: login.php');
die();
}
}

// All output text below this line will be displayed
// to the users that are authenticated.

echo "<h1>Access Granted</h1>";
echo "You see? It travelled over these two pages.<br><br>";
echo "You are authenticated as " . $_SESSION['user'] . "<br>";
echo "The MD5 checksum of your password is " . $_SESSION['pass'];

?>


As usual, we'll take a closer look at the code:

// Start the login session
session_start();

if (!$_SESSION['user'] || !$_SESSION['pass']) {

// What to do if the user hasn't logged in
// We'll just redirect them to the login page.
header('Location: login.php');
die();


In this snippet we're checking to see if the session variables have been set. If they haven't, then we redirect them to the login.php again. In case you're wondering why we're using die after the header(), it's for extra security. A hacker can for example make his own browser that ignores header redirects. Better safe than sorry.

} else {

// If the session variables exist, check to see
// if the user has access.

$db = mysql_connect('localhost', 'dbuser', 'dbpass') or die("Couldn't connect to the database.");
mysql_select_db('dbname') or die("Couldn't select the database");

$result = mysql_query("SELECT count(id) FROM users WHERE password='$_SESSION[pass]' AND username='$_SESSION[user]'") or die("Couldn't query the user-database.");
$num = mysql_result($result, 0);

if (!$num) {
// If the credentials didn't match,
// redirect the user to the login screen.
header('Location: login.php');
die();
}
}


This code is almost exactly the same as login.php. We don't have to add slashes here because they were already added in login.php. Again, you can see we're using die() after the header() redirect.

// All output text below this line will be displayed
// to the users that are authenticated.

echo "<h1>Access Granted</h1>";
echo "You see? It travelled over these two pages.<br><br>";
echo "You are authenticated as " . $_SESSION['user'] . "<br>";
echo "The MD5 checksum of your password is " . $_SESSION['pass'];


This is just placeholder text. Feel free to replace it with whatever you want.

Try authenticating yourself, and see how the session transfers the login information between the pages.

Instead of copying the code in page2.php into all pages you want authentication on, you can name it auth.php, and include() it in all of the pages you want authentication on.

All you have to do to delete the session data, thus logging yourself out, is to make a PHP script with this code:

<?PHP
session_start();
session_destroy();

echo "You have been successfully logged out.";
?>

blog comments powered by Disqus
MYSQL ARTICLES

- MySQL and BLOBs
- Two Lessons in ASP and MySQL
- Lord Of The Strings Part 2
- Lord Of The Strings Part 1
- Importing Data into MySQL with Navicat
- Building a Sustainable Web Site
- Creating An Online Photo Album with PHP and ...
- Creating An Online Photo Album with PHP and ...
- PhpED 3.2 More Features Than You Can Poke ...
- Creating An Online Photo Album with PHP and ...
- Creating An Online Photo Album with PHP and ...
- Security and Sessions in PHP
- Setup Your Personal Reminder System Using PHP
- Create a IP-Country Database Using PERL and ...
- Developing a Dynamic Document Search in PHP ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials