[script] Password Protect web pages/site using PHP and MySQL
The 'engine' behind this Password Protect web pages / sites using PHP script:
PHP Code:
<?php
/**
* @domain: DESILVA.BIZ
* @file: EXAMPLE_SESSION_FUNCTIONS.PHP
* @author: J de Silva
* @website: [url]www.desilva.biz[/url]
* @email: scripts[AT]desilva[DOT]biz
* @copyright: Gen.I designs
* @date: July 24th, 2003
* @version: n/a
* @about: The 'engine' behind a simple PHP / MySQL session based
login / password protecting web pages script. Contains
key functions for the LOGIN system.
*
/*===================================*/
ini_set( 'session.name', 's' );
/* the URL to the login page is defined... */
define( 'URL_LOGIN_PAGE', '/example_login.php' );
// start the session...
session_start();
/* One of the main functions of this included script is
to check that the page including this script is
being used by a valid user. There is ONE exception:
when the person is actually LOGGING IN. */
if( !defined('LOGGING_IN') )
{
verify_if_valid_user();
}
/* All the relevant functions are listed below. */
//------------------------------------------------
function match_user_in_db( $user, $pass )
{
// it would be wiser for you to connect to the db using
// a custom function here but for the purpose of this tutorial
// I am including the connection right here...
$conn = mysql_connect( 'localhost', 'root', '' );
mysql_select_db( 'mw' );
$sql = 'SELECT `username`
FROM `account`
WHERE `username` = "'.$user.'"
AND `password` = "'.$pass.'"';
$result = mysql_query( $sql, $conn );
if( mysql_num_rows($result)==1 )
{
$_SESSION['valid_user'] = mysql_result( $result, 0, 0 );
/* the php.ini setting for 'session.use_trans_sid' should be 1
for the following line to work, so if this script doesn't seem
to be working well for you, you know where to look! */
die( header('location:/example_secret_page_1.php?'.SID) );
}
else
{
die( header('location:'.URL_LOGIN_PAGE) );
}
}
function process_login()
{
/* Used ONLY in the LOGIN page. */
$username = mysql_escape_string( trim($_POST['username']) );
/* if you store the passwords without using md5,
of course, edit the following line too. */
$password = md5( trim($_POST['password']) );
match_user_in_db( $username, $password );
}
function process_logout()
{
/* used ONLY in the LOGOUT page. */
session_destroy();
unset( $_SESSION );
die( header('location:'.URL_LOGIN_PAGE) );
}
function verify_if_valid_user()
{
if( !isset($_SESSION['valid_user']) )
{
// user not logged in yet!
// re-direct them to the login page
die( header('location:'.URL_LOGIN_PAGE) );
}
}
?>