Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

thread434-1256073 - jpadie code 1

Status
Not open for further replies.

keepingbusy

Programmer
Apr 9, 2000
1,470
GB
Hi

I've had some responses to a question about using a login script on other threads to only allow registered individuals access to a website.

Below is jpadie's code from one of those threads and I have a few questions:

1. If I set up a table for allowed users to the site in phpmyadmin, what do I need to call it and what are the field names/attributes?
2. How do I remove the Register New User Button (we will do this via phpmyadmin)?
3. By adding the single line of code (also shown below) can someone confim that will this stop anyone from viewing our site unless they have "Logged in" correctly.

The security of the site is not an issue but we only want selected visitors who use the correct login procedure (it's a site selling Music DVD's and CD's to the trade/business users)

I am new to php and only been involved in the setup of two websites using oscommerce so willing to have a go. The thread mentioned on the subject line (thread434-1256073) has now been closed so here is jpadie's code:
Code:
<?php 
session_start();
?>
<style>
fieldset {border-color:#0000FF; width:60%;}
table:{width:100%; border-collapse:collapse;}
</style>
<?
define ("TIMEOUT", 10); //set the login time out in minutes

/*    DEBUG 
echo "session vars<br/>";
print_r($_SESSION);
echo "<br/>";
echo "post vars<br/>";
print_r($_POST);
*/

//use this script by just including the page at the top of every real page
if (!loggedon()):  
    login();  
else:
    ##this line is included for debug. 
    #normally you would just let the script continue
    echo "You are logged on<br/> click<a href=\"". $_SERVER['PHP_SELF']."?logout=true\"> here </a> to logout";
endif;

function loggedon()
{
//this tests the current status
    if (isset ($_SESSION['loggedon'])):
        if (($_SESSION['lastaccess'] + (60 * TIMEOUT)) < strtotime("now")):
            logout("Session has timed out");
            exit;
        else:
            $_SESSION['lastaccess'] = strtotime("now");
            
            if ((isset($_POST['submit']) && ($_POST['submit'] === "Change Password"))):
                process_change_password();
                exit;
            elseif (isset($_SESSION['flagpwd']) && ($_SESSION['flagpwd'] === true)):
                changepassword();
                exit;
            elseif (isset($_GET['logout'])):
                logout();
                exit;
            else:
                return true;
            endif;
        endif;
    else:
        return false;
    endif;
}

function render_user_form($msg=NULL)
{
?>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<fieldset>
<legend>Login</legend>
<table>
<input type="hidden" name="uniqstamp" value="<?=strtotime("now")?>" />
<? if (!is_null($msg)):?>
<tr><td colspan="2"><?=$msg?></td></tr>
<? endif; ?>
<tr><td>Username:</td><td><input type="text" name="username"  /></td></tr>
<tr><td>Password:</td><td><input type="password" name="pwd" /></td></tr>
<tr><td colspan="2"><input type="reset" name="reset" value="Clear Form" />&nbsp;<input type="submit" name="submit" value="Login" /></td></tr>
<tr><td colspan="2"><input type="submit" name="submit" value="Reset Password" /><input type="submit" name="submit" value="Register New User" /></td></tr>
</table>
</p>
</fieldset>
</form>
<?
}

function logout($msg=NULL)
{
    unset($_SESSION['username']);
    unset($_SESSION['loggedon']);
    unset($_SESSION['lastaccess']);

    render_user_form ($msg);
    exit;
}
//master script
function display_reset_password_form()
{
?>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<fieldset>
<legend>Reset</legend>
<table>
<tr><td>Email:</td><td><input type="text" name="email"  /></td></tr>
<tr><td colspan="2"><input type="reset" name="reset" value="Clear Form" />&nbsp;<input type="submit" name="submit" value="Submit Reset Request" /></td></tr>
</table>
</fieldset>
</form>
<?
}

function login()
{
    if (!isset ($_POST['submit'])):
        logout();
    endif;
    
    switch ($_POST['submit']):
        case "Reset Password":
            unset($_SESSION['username']);
            unset($_SESSION['loggedon']);
            unset($_SESSION['lastaccess']);
            display_reset_password_form();
            break;
        case "Login":
            if (!test_fresh_login()):
                logout("You cannot re-login through the back button");
                exit;
            endif;
            
            if (!validlogon()):
                logout("Either username or password is incorrect");
            else:
                $_SESSION['username'] = $_POST['username'];
                $_SESSION['loggedon'] = true;
                $_SESSION['lastaccess'] = strtotime("now");
                unset ($_POST);
                header("Location: ".$_SERVER['PHP_SELF']);
            endif;
        break;
        case "Register New User":
            display_new_user_form();
            exit;
        break;
        case "Register":
            process_registration();
        break;
        case "Submit Reset Request":
            resetpassword();
        break;
        default:
            logout();
    endswitch;
}
function display_new_user_form($msg=NULL)
{

$username ="";
$email="";
?>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<fieldset>
<legend>Login</legend>
<table>
<input type="hidden" name="uniqstamp" value="<?=strtotime("now")?>" />
<? if (!is_null($msg)):?>
<tr><td colspan="2"><?=$msg?></td></tr>
<? 
extract ($_POST);
endif; ?>
<tr><td>Username:</td><td><input type="text" name="username"  value="<?=$username?>"/></td></tr>
<tr><td>Email:</td><td><input type="email" name="email" value="<?=$email?>"/></td></tr>
<tr><td>Password:</td><td><input type="password" name="pwd" /></td></tr>
<tr><td>Confirm Password:</td><td><input type="password" name="pwd_confirm" /></td></tr>
<tr><td colspan="2"><input type="reset" name="reset" value="Clear Form" />&nbsp;<input type="submit" name="submit" value="Register" /></td></tr>
</table>
</fieldset>
</form>
<?
}
function process_registration()
{
    $msg = "";
    if (!isset ($_POST['username']) || empty($_POST['username'])):
        $msg .= "You must supply a username<br/>";    
    endif;
    if (!isset ($_POST['email']) || empty($_POST['email'])):
        $msg .= "You must supply an email address<br/>";    
    endif;
    if (!empty($_POST['pwd'])):
        if ($_POST['pwd'] != $_POST['pwd_confirm']):
        $msg .= "Your password confirmation must match<br/>";    
        endif;
    endif;
    dbconnect();
    $sql = "Select 
                count(*) as cnt 
            from 
                usertable 
            where 
                username='".trim($_POST['username'])."'";
    $result = mysql_query ($sql);
    $row = mysql_fetch_assoc($result);
    if ($row['cnt'] != 0):
        $msg .= "Your chosen username is already in use<br/>";
    endif;
    
    if (!empty($msg)):
        display_new_user_form($msg);
        exit;
    endif;
    
    //all validated now
    
    $sql = "
        insert into
            usertable
        set
            username = '".trim($_POST['username'])."',
            pwd = '".md5(trim($_POST['pwd']))."',
            email = '".trim($_POST['email'])."'";
    
    mysql_query($sql);
    if (mysql_affected_rows() != 1):
        die(mysql_error());
    endif;
    //now log the user on
    $_SESSION['username'] = $_POST['username'];
    $_SESSION['loggedon'] = true;
    $_SESSION['lastaccess'] = strtotime("now");
    unset ($_POST);
    header("Location: ".$_SERVER['PHP_SELF']);

}
function process_change_password()
{
    $msg = "";
    if (!isset ($_POST['username']) && !empty($_POST['username'])):
        loggedout("something wrong here");
        exit;
    endif;
    if (!empty($_POST['pwd'])):
        if ($_POST['pwd'] != $_POST['pwd_confirm']):
        $msg .= "Your password confirmation must match<br/>";    
        endif;
    endif;
    if (!empty($msg)):
        changepassword($msg);
        exit;
    endif;
    $sql = "
        update 
            usertable
        set
            pwd = '".md5(trim($_POST['pwd']))."',
            pwdchange = '0'
        where
            username = '".trim($_POST['username'])."'";
    dbconnect();
    if (!mysql_query($sql)):
        die("something wrong here ".mysql_error() . " affected rows are ".mysql_affected_rows() . " and sql is $sql");
    endif;
    unset ($_POST);
    $_SESSION['flagpwd'] = false;
    echo "Password changed.<br/> click <a href=\"".$_SERVER['PHP_SELF']."\">here</a> to continue";
}
function test_fresh_login()
{
    if (isset($_SESSION['uniqstamp'])):
        if (isset($_POST['uniqstamp'])):
            if ($_SESSION['uniqstamp'] === $_POST['uniqstamp']):
                return false;
            else:
                return true;
            endif;
        else:
            //something wrong here
            logout ("You have arrived here unexpectedly");
            exit;
        endif;
        $_SESSION = array();
        session_destroy();
    else:
        return true;
    endif;
}
function dbconnect()
{
    @mysql_connect("localhost", "root","root") or die ("unable to connect to server");

    @mysql_select_db("test") or die ("unable to connect to database");
    
    /*
    note you need a table called usertable
    CREATE TABLE `usertable` (
    `id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `username` VARCHAR( 255 ) NOT NULL ,
    `pwd` VARCHAR( 255 ) NOT NULL ,
    `email` VARCHAR( 255 ) NOT NULL ,
    `pwdchange` int (1) NOT NULL,
    UNIQUE (
    `username` 
    )
    ) TYPE = innodb;
    */
    
}
function validlogon()
{
    if (!isset ($_POST['username']) || !isset ($_POST['pwd'])):
        return false;
    endif;
    dbconnect();
    
    $sql = "
        Select 
            pwdchange
        from 
            usertable 
        where 
            username = '".trim($_POST['username']) ."'
            and
            pwd = '".md5(trim($_POST['pwd']))."'";
            

    $results = mysql_query($sql);
    $row = mysql_fetch_assoc($results);
    if (mysql_num_rows($results) != 0):
        if ($row['pwdchange'] !='1'):
            $_SESSION['flagpwd'] = false;
        else:
            $_SESSION['flagpwd'] = true;
        endif;
        $_SESSION['uniqstamp'] = $_POST['uniqstamp'];
        return true;
    else:
        return false;
    endif;
}    
function changepassword($msg=NULL)
{
?>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<fieldset>
<legend>Change Password</legend>
<table>
<? if (!is_null($msg)):?>
<tr><td colspan="2"><?=$msg?></td></tr>
<? endif; ?>
<input type="hidden" name="username" value="<?=$_SESSION['username']?>" />
<tr><td>Password:</td><td><input type="password" name="pwd" /></td></tr>
<tr><td>Confirm Password:</td><td><input type="password" name="pwd_confirm" /></td></tr>
<tr><td colspan="2"><input type="reset" name="reset" value="Clear Form" />&nbsp;<input type="submit" name="submit" value="Change Password" /></td></tr>
</table>
</fieldset>
</form>
<?
}
function resetpassword()
{
dbconnect();
    
    $password = "pcworld";
    $sql = "
        Update 
            usertable
        set
            pwd = '".md5(trim($password))."',
            pwdchange = '1'
        where
            email ='".trim($_POST['email'])."'";
    
    echo $sql ."<br/>";
    mysql_query($sql); //errors deliberately suppressed
    if (mysql_affected_rows() != 0):
        mail(trim($_POST['email']),"New password", "Your new password is $password");
    endif;
    die ("If you have provided a correct email address that is in our system, an email with your new password will be sent to you shortly. <br/>click<a href=\"". $_SERVER['PHP_SELF']."\"> here </a> to login<br/>DEBUG: password is $password. ");
}
?>
and the single line at the header of every php file within our website is supposed to be:
Code:
require_once "path/to/login.php";

Some help not the sollution would be very much appreciated.

Thanks in anticipation guys

Lee


Windows XP
Visual FoxPro Version 6 & 9
 
I forgot to mention that if we already have a table with users is it possible to use that for the login? I don't want to complicate things as it would be acceptable for visitors to login as mentioned above, view the site and if they want to place an order, just use their details to login to their account.

Hope that makes sense!

Lee


Windows XP
Visual FoxPro Version 6 & 9
 
your questions are:

1. what do you need to call you users table?
2. what fields are required?
3. is all you need to do to secure your pages to add the require_once code at the top of a page?
4. how do you remove the register new user button
5. can you use an alternative user table.

answers

1. anything you like. you will need to make changes to the sql throughout the code
2. the minimum are a unique username (userName), password (pwd) and email address (email). these will be varchar (255). if you do not use the table definition in the code you will need to make other changes throughout the code.
3. yes
4. take this code out of render_user_form()
Code:
<input type="submit" name="submit" value="Register New User" />
and make the necessary cleanup changes elsewhere in the script.

5. yes. but changes will be necessary. you might be better off using the activeUser class I mentioned in a recent post.

but beware. I post these code snips not so that people can just use them as they are but so that they can be taken and examined offline. learned from and adapted to your own use. don't take anyone's code (whatever the licence) and reuse it without understanding every element of it.

login scripts are a great way to learn coding. they are useful, required CRUD database manipulation and are easy to write.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top