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

Problem using the generated password with my php code.

Status
Not open for further replies.

keith23

Technical User
May 26, 2005
97
0
0
NL
Hi all i created a page that it generates log in password for users. Beleow u see a part of the code and it generates the password and it supposed to email it. The problem is that i am testing this locally and it does not email the password since i do not have any smtp for email . Therefore, i went to mysql db and found the pass word that created for me as some thing like this :*BEE77AB0FB9380C

I tried to use that but it does not work and i keep getting Access Denied massage from access.php part!! I be happy if an expert give me a way so that i be able to use the assigned password and be able to test my prog .Thanks


registerationpage.php code
Code:
[B]$newpass = substr(md5(time()),0,6);[/B]

    
    
    $sql = "INSERT INTO user SET
              userid = '$_POST[newid]',
              password = PASSWORD('$newpass'),
              fullname = '$_POST[newname]',
              email = '$_POST[newemail]',
              notes = '$_POST[newnotes]'";
    if (!mysql_query($sql))
        error('A database error occurred in processing your '.
              'submission.\\nIf this error persists, please '.
              'contact you@example.com.\\n' . mysql_error());
              
    // Email the new password to the person.
    [B]$message = "   your new password    
     userid: $_POST[newid]
    password: $newpass               ";

    mail($_POST['newemail'],"Your Password for the Project Website",
         $message, "From:Your Name <you@example.com>");[/B]


part of access.php code


Code:
dbConnect("test2");
[B]$sql = "SELECT * FROM user WHERE
        userid = '$uid' AND password = PASSWORD('$pwd')";
$result = mysql_query($sql);
if (!$result) {
  error('A database error occurred while checking your '.
        'login details.\\nIf this error persists, please '.
        'contact you@example.com.');
}[/B]
if (mysql_num_rows($result) == 0) {
  unset($_SESSION['uid']);
  unset($_SESSION['pwd']);
  ?>
  <!DOCTYPE html PUBLIC "-//W3C/DTD XHTML 1.0 Transitional//EN"
    "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
  <html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
  <head>
    <title> Access Denied </title>
    <meta http-equiv="Content-Type"
      content="text/html; charset=iso-8859-1" />
  </head>
  <body>
  [B]<h1> Access Denied </h1>[/B]
  <p>Your user ID or password is incorrect, or you are not a
     registered user on this site. To try logging in again, click
     <a href="<?=$_SERVER['PHP_SELF']?>">here</a>. To register for instant
     access, click <a href="signup.php">here</a>.</p>
  </body>
  </html>
  <?php
  exit;
}

$username = mysql_result($result,0,'fullname');
?>



Code:
<?php include ' [B]access.php'[/B]; ?>
<!DOCTYPE html PUBLIC "-//W3C/DTD XHTML 1.0 Transitional//EN"
  "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
  <title> Members-Only Page </title>
  <meta http-equiv="Content-Type"
    content="text/html; charset=iso-8859-1
</head>
<body>
<p>Welcome, <?=$username?>! [B]You have entered a members-only area
   of the site. Don't you feel special?</p>[/B]
</body>
</html>
 
Therefore, i went to mysql db and found the pass word that created for me as some thing like this :*BEE77AB0FB9380C

that's not your password. that's is the form in which your password is stored in the database.
your password is that which is created as $newpass by this line below:

Code:
$newpass = substr(md5(time()),0,6);

also, as advised to you in another recent post, you cannot use password as a field name if you do not enclose it in backticks. thus this line in access.php won't work

Code:
$sql = "SELECT * FROM user WHERE
        userid = '$uid' AND password = PASSWORD('$pwd')";

and neither will this line in your first script
Code:
    $sql = "INSERT INTO user SET
              userid = '$_POST[newid]',
              password = PASSWORD('$newpass'),
              fullname = '$_POST[newname]',
              email = '$_POST[newemail]',
              notes = '$_POST[newnotes]'";
put backticks around the field names and make sure you are using the right password.


 
If you are new to programming in php and MySQL, what you may not understand is that the md5 is an encryption function

what is happening is a time value
Example: 05:19:25 is being encrypted by md5 function into the BEE77AB0FB9380C

but your true password is still the 051925

removing the md5 function will give you the text representation
$newpass = substr(time(),0,6);

if you retain the md5 function
what you would need to do is have them login using the 051925 where

$_SESSION['pwd'] = "051925";

and then convert(encrypt) that using the md5 function again
example:

$loginpass = md5($_SESSION['pwd']);

then do your Database routine

$sql = "SELECT * FROM user WHERE
userid = '$uid' AND password = $loginpass";

I hope that helps explain it


 
KarterJK

are you sure of your advice?

It seems to me that Keith 23 said:
Therefore, i went to mysql db and found the pass word that created for me as some thing like this :*BEE77AB0FB9380C

and he posted code that suggests he put the value into the database by
Code:
 $sql = "INSERT INTO user SET
              userid = '$_POST[newid]',
              password = PASSWORD('$newpass'),
              fullname = '$_POST[newname]',
              email = '$_POST[newemail]',
              notes = '$_POST[newnotes]'";

this suggests, to me, that he is inserting the
1. mysql password crypted version of
2. the first 6 letters of the
3. md5 value of
4. time().

not just the md5 value of time.

you say
but your true password is still the 051925

the way I read Keith23's code line:
Code:
$newpass = substr(md5(time()),0,6);
is that the password is the combination of 2-4 of my list above and NOT the time() value.
you also suggest a "database routine" of :
Code:
$sql = "SELECT * FROM user WHERE
        userid = '$uid' AND password = $loginpass";

i *think* that "password" is a reserved word. Would not Keith23 need to put backticks around the word to identify it as a field?
 
Many thanks for all of you:
jpadie :
If : *BEE77AB0FB9380C is not my password then what is the value of my password.
I changed

$newpass = substr(md5(time()),0,6); to
$newpass = substr(time(),0,6);

echo $newpass;

The value that it printed is :114029 on database it produced : *EC5CAD1D6304B59

I tried using 114029 but it did not work!!!


Do u mean i need to change the line that checks the password in db before allowing me to
view the protected page to :

Code:
$sql = "SELECT * FROM user WHERE
        userid = '$uid' AND (`password`) = PASSWORD('$pwd')";
Furthermore, do u mean i need to change the line that inserts the password to db to :

Code:
$sql = "INSERT INTO user SET
              userid = '$_POST[newid]',
              (`password`) = PASSWORD('$newpass'),
              fullname = '$_POST[newname]',
              email = '$_POST[newemail]',
              notes = '$_POST[newnotes]'";
i even tried output value of generated password by :

Code:
$newpass = substr(md5(time()),0,6);
The value was printed as 75ec31 and in db value was *A099781E9E8008C !! Both of these values
did not allow me view the protected page!!

It is very strange that it writes the value in db but when i try to log in it does not work!!
i tried both printed value and db value and non of them allow me to view the protected page!! I be
happy if you guys tell me what is wrong here.Thanks


KarterJK . I could not understand this part ;

Code:
if you retain the md5 function 
what you would need to do is have them login using the 051925 where

$_SESSION['pwd'] = "051925";

and then convert(encrypt) that using the md5 function again
example:

$loginpass = md5($_SESSION['pwd']);

then do your Database routine


complete access code:
Code:
//start of php code
include_once 'common.php';
include_once 'db.php';

session_start();

$uid = isset($_POST['uid']) ? $_POST['uid'] : $_SESSION['uid'];
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : $_SESSION['pwd'];

if(!isset($uid)) {
  ?>
  <!DOCTYPE html PUBLIC "-//W3C/DTD XHTML 1.0 Transitional//EN"
    "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
  <html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
  <head>
    <title> Please Log In for Access </title>
    <meta http-equiv="Content-Type"
      content="text/html; charset=iso-8859-1" />
  </head>
  <body>
  <h1> Login Required </h1>
  <p>You must log in to access this area of the site. If you are
     not a registered user, <a href="signup.php">click here</a>
     to sign up for instant access!</p>
  <p><form method="post" action="<?=$_SERVER['PHP_SELF']?>">
    User ID: <input type="text" name="uid" size="8" /><br />
    Password: <input type="password" name="pwd" SIZE="8" /><br />
    <input type="submit" value="Log in" />
  </form></p>
  </body>
  </html>
  <?php
  exit;
}

$_SESSION['uid'] = $uid;
$_SESSION['pwd'] = $pwd;


[B]dbConnect("test2");
$sql = "SELECT * FROM user WHERE
        userid = '$uid' AND password = PASSWORD('$pwd')";
$result = mysql_query($sql);
if (!$result) {
  error('A database error occurred while checking your '.
        'login details.\\nIf this error persists, please '.
        'contact you@example.com.');
}

if (mysql_num_rows($result) == 0) {
  unset($_SESSION['uid']);
  unset($_SESSION['pwd']);[/B]  ?>
  <!DOCTYPE html PUBLIC "-//W3C/DTD XHTML 1.0 Transitional//EN"
    "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
  <html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
  <head>
    <title> Access Denied </title>
    <meta http-equiv="Content-Type"
      content="text/html; charset=iso-8859-1" />
  </head>
  <body>
  <h1> Access Denied </h1>
  <p>Your user ID or password is incorrect, or you are not a
     registered user on this site. To try logging in again, click
     <a href="<?=$_SERVER['PHP_SELF']?>">here</a>. To register for instant
     access, click <a href="signup.php">here</a>.</p>
  </body>
  </html>
  <?php
  exit;
}

$username = mysql_result($result,0,'fullname');

// end of php code here
 
Keith23

don't put brackets around the fieldname - just the backticks. make this change throughout.
Code:
$sql = "SELECT * FROM user WHERE
        userid = '$uid' AND (`password`) = PASSWORD('$pwd')";
HOWEVER, in your posted script above you are checking the validity of a logon as follows:
Code:
$sql = "SELECT * FROM user WHERE
        userid = '$uid' AND password = PASSWORD('$pwd')";
you need to put backticks in
Code:
$sql = "SELECT * FROM user WHERE
        userid = '$uid' AND `password` = PASSWORD('$pwd')";

also your starting declaration
Code:
$uid = isset($_POST['uid']) ? $_POST['uid'] : $_SESSION['uid'];
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : $_SESSION['pwd'];
should be changed to
Code:
$uid = isset($_POST['uid']) ? $_POST['uid'] : isset($_SESSION['uid']) ? $_SESSION['uid'] : "";
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : isset($_SESSION['pwd'])? $_SESSION['pwd'] : "";
to avoid errors. also change the !isset($uid) to !empty($uid)

overall - i think your code could be improved upon from a security perspective but i guess you're using this as a learning experience. some tips

+ don't use select * and mysql_num_rows to determine whether a record exists. use count(*) instead
+ don't use mysql's password function. instead use php's md5 and store the plain text md5 hash value in the db.

i have written a complete log in and user script for previous tek-tips posters. it was written for ease of use and learnability. if you would like a copy let me know by posting back.

Justin
 
Many thanks for u reply . i made all those changes u suggested.Those changes in bold as u see beleow.But it does not accept my password.I tried the passwored that shows in echo $newpass; .Alos when i use your code:

Code:
[B]$uid = isset($_POST['uid']) ? $_POST['uid'] : isset($_SESSION['uid']) ? $_SESSION['uid'] : "";
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : isset($_SESSION['pwd'])? $_SESSION['pwd'] : "";[/B]

instead of current code i do not get the log in form when i access protected page:


part of access.php code(top part)
Code:
//$uid = isset($_POST['uid']) ? $_POST['uid'] : $_SESSION['uid'];
//$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : $_SESSION['pwd'];

[B]$uid = isset($_POST['uid']) ? $_POST['uid'] : isset($_SESSION['uid']) ? $_SESSION['uid'] : "";
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : isset($_SESSION['pwd'])? $_SESSION['pwd'] : "";[/B]

It is strange that value shown in [B] echo $newpass;[/B]   is not the same as the one stored in db!! Both of them does not allow me log in!! Yes i am using this as experience to learn i be happy if i get that code and help understanding what is wrong here in my code.Thanks


//if(!isset($uid)){
[B]if(!empty($uid)) { [/B]


part of access.php code
Code:
$_SESSION['uid'] = $uid;
$_SESSION['pwd'] = $pwd;

dbConnect("test2");
$sql = "SELECT * FROM user WHERE
        userid = '$uid' AND [B]`password`[/B] = PASSWORD('$pwd')";
$result = mysql_query($sql);
if (!$result) {
  error('A database error occurred while checking your '.
        'login details.\\nIf this error persists, please '.
        'contact you@example.com.');
}

if (mysql_num_rows($result) == 0) {
  unset($_SESSION['uid']);
  unset($_SESSION['pwd']);

part of code:
Code:
    $newpass = substr(md5(time()),0,6);
    //$newpass = time();
    //$newpass = substr(time(),0,6);

    [B] echo $newpass;[/B]    
    $sql = "INSERT INTO user SET
              userid = '$_POST[newid]',
              [B]`password`[/B] = PASSWORD('$newpass'),
              fullname = '$_POST[newname]',
              email = '$_POST[newemail]',
              notes = '$_POST[newnotes]'";
    if (!mysql_query($sql))
        error('A database error occurred in processing your '.
              'submission.\\nIf this error persists, please '.
              'contact you@example.com.\\n' . mysql_error());
              
    // Email the new password to the person.
 
instead of current code i do not get the log in form when i access protected page:
as i posted above - you need to change the isset($uid) test to empty($uid)

It is strange that value shown in echo $newpass; is not the same as the one stored in db!!

it will NEVER be the same as you are crypting the value through the use of the mysql PASSWORD function.

my login code is below. instructions are embedded in the code
Code:
<?php 
session_start();
?>
<style>
fieldset {border-color:#0000FF; width:60%;}
table:{width:100%; border-collapse:collapse;}
</style>
<?
/*	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 * 1)) < 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)
{
	$_SESSION = array();
	session_destroy();
	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":
			$_SESSION = array();
			session_destroy();
			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. ");
}
?>
 
i have tried to fix up your access.php file. i have not been able to test it on my servers so i can't guarantee it will work:

access.php
Code:
<?
//start of php code
include_once 'common.php';
include_once 'db.php';

session_start();

$uid = isset($_POST['uid']) ? $_POST['uid'] : isset($_SESSION['uid'])?$_SESSION['uid'] : "";
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : isset($_SESSION['pwd'])?$_SESSION['pwd'] : "";

if(empty($uid)) :
  ?>
  <!DOCTYPE html PUBLIC "-//W3C/DTD XHTML 1.0 Transitional//EN"
    "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
  <html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
  <head>
    <title> Please Log In for Access </title>
    <meta http-equiv="Content-Type"
      content="text/html; charset=iso-8859-1" />
  </head>
  <body>
  <h1> Login Required </h1>
  <p>You must log in to access this area of the site. If you are
     not a registered user, <a href="signup.php">click here</a>
     to sign up for instant access!</p>
  <p><form method="post" action="<?=$_SERVER['PHP_SELF']?>">
    User ID: <input type="text" name="uid" size="8" /><br />
    Password: <input type="password" name="pwd" SIZE="8" /><br />
    <input type="submit" value="Log in" />
  </form></p>
  </body>
  </html>
  <?php
  exit;
else:


dbConnect("test2");
$sql = "	SELECT 	
				count(*) as cnt
			FROM 
				user 
			WHERE
        		userid = '$uid' 
				AND 
				`password` = PASSWORD('$pwd')";

$result = mysql_query($sql);

if (!$result) {
  error('A database error occurred while checking your '.
        'login details.\\nIf this error persists, please '.
        'contact you@example.com.');
}
$row = mysql_fetch_assoc($result);
if ($row['cnt'] === 0):
  unset($_SESSION['uid']);
  unset($_SESSION['pwd']);
  ?>
  <!DOCTYPE html PUBLIC "-//W3C/DTD XHTML 1.0 Transitional//EN"
    "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
  <html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
  <head>
    <title> Access Denied </title>
    <meta http-equiv="Content-Type"
      content="text/html; charset=iso-8859-1" />
  </head>
  <body>
  <h1> Access Denied </h1>
  <p>Your user ID or password is incorrect, or you are not a
     registered user on this site. To try logging in again, click
     <a href="<?=$_SERVER['PHP_SELF']?>">here</a>. To register for instant
     access, click <a href="signup.php">here</a>.</p>
  </body>
  </html>
  <?php
else:
	$_SESSION['uid'] = $uid;
	$_SESSION['pwd'] = $pwd;
  	echo "logged in just fine";
endif;
  exit;
endif;
 
Many thanks to u jpadie . i tried your log in scrip codeand after registering new account i get the following error but it writes the data in db:

Code:
Warning: Cannot modify header information - headers already sent by (output started at c:\wamp\[URL unfurl="true"]www\wimpy5recursive\accesscontrol\test.php:4)[/URL] in c:\wamp\[URL unfurl="true"]www\wimpy5recursive\accesscontrol\test.php[/URL] on line 220

part of code where error pointing to
Code:
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']); [B]==> line 220[/B]

Furthermore, i tried to run the script that u edited but when i put pass and user name nothing happens and i checked db the user name was created but when i use value of password echo it does not work!!

protected page code
Code:
<?php include [B]'access.php'[/B]; ?>
<!DOCTYPE html PUBLIC "-//W3C/DTD XHTML 1.0 Transitional//EN"
  "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
  <title> Members-Only Page </title>
  <meta http-equiv="Content-Type"
    content="text/html; charset=iso-8859-1
</head>
<body>
<p>Welcome, <?=$username?>! You have entered a members-only area
   of the site. Don't you feel special?</p>
</body>
</html>
 
Warning: Cannot modify header information - headers already sent by (output started at c:\wamp\ in c:\wamp\ on line 220
oops. sorry, i added some style information to help the display. i will fix this and post it back.

for your script - i guess it's difficult working piecemeal. can you email me the files you are using and i will set them up. the error will be very straightforward - it always is! my email address is jpadie AT hotmail DOT COM
 
Many thanks jpadie for helping me in learning process. I send u an email with file attached . I also paste the download link.looking foward for your post back!

Code:
[URL unfurl="true"]http://s14.yousendit.com/d.aspx?id=1GWROQ035RHWP23AJSEIBSG65F[/URL]
 
email from Keith23
Hi jpadie this keith23 from tek tips fourm. I enclused a copy of the php login script. My intention is to learn how to make a login script that protect certain pages and once the user loged in other protected pages know that u already loged in they do not ask for log in name again. Obviously i want it to expire with in certian time.Furthermore, could u show me how to pass login name to diffrent page and use them when needed such as db query.Thanks

your script already does a lot of what you want. you store a valid logon in the session variables which means that, so long as you start the session on each page (session_start()) you will have access to the username.

for the timeout - i would add the time of each page refresh to the session stack. then each page refresh test to see whether the delta is longer than your time out value. if it is, then kick the user out.

I have fixed your files and tried to send them back to you but the email bounced. Please post a mail address so i can return your files.

thanks
Justin
 
jpadide my email is method007 at g mail.
 
thanks. the files have been sent back to you. We should continue the conversation on this chain for the forum's benefit.

thanks
Justin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top