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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

PHP Login Script

Status
Not open for further replies.

trent101

Programmer
Nov 4, 2005
50
0
0
AU
Hey,

I am really new to php and need some guidence.

I can program in c++ but never really tried web programming. I have a job where I have to build a website, in which a user can register there details ( I'm assuming I would hook this up to a mysql or access db), and then they can login to the members section once they have signed up.

Does anyone know of any good tutorials or websites that can help me out with what I need to do?

I have begun reading lots of php docs but there is so much out there I am getting a little lost.

Any help is appreciated.
 
i think i wrote this one quite recently but my version control has uncharacteristically gone a bit screwy.

the sql code for the table you need is in comments at the top of the file.

just save the code as login.php and, in the pages you wish to protect, put this code at the top:
Code:
require_once "path/to/login.php";

note that the login code starts its own session. if you are already using sessions elsewhere then delete the session_start line.

the code has a timeout feature which is defined at the start of the file.

It does not have a rememberme function as this is somewhat inconsistent with a timeout!

the 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. ");
}
?>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top