Jump to content


Photo

Adding a change pass function to login & register PHP/JQuery/MySQL script

help login register changepass change password

  • This topic is locked This topic is locked
4 replies to this topic

#1 Aphex

Aphex

    Newbie

  • New Members
  • Pip
  • 6 posts

Posted 22 January 2013 - 12:02 AM

Hello. I was wondering whether I could request some help about adding a change pass function to my login / register script on PHP/JQuery/MySQL. I have started the change pass function a little (the form is fully done and checks whether the required fields are filled in) but the rest is way above my current knowledge that involves PHP, I am more of a HTML person.
Also, I would highly appreciate it if you could let me know whether this is vulnerable to SQL injection, I doubt it is because I've added some extra "mysql_real_escape_string();" to the script but all comments would help. I am useless at PHP <.<
I have marked in the code where I have started the change pass function to make it a little easier to find.

Here is the code:

<?php
error_reporting(E_ALL ^ E_NOTICE);
define('INCLUDE_CHECK',true);
require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('tzLogin');
// Starting the session
session_set_cookie_params(2*7*24*60*60);
// Making the cookie live for 2 weeks
session_start();
if($_SESSION['id'] && !isset($_COOKIE['tzRemember']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the tzRemember cookie (browser restart)
// and you have not checked the rememberMe checkbox:
$_SESSION = array();
session_destroy();

// Destroy the session
}

if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();

header("Location: http://127.0.0.1/");
exit;
}
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted

$err = array();
// Will hold our errors


if(!$_POST['logusername'] || !$_POST['password'])
  $err[] = 'All fields are required.';

if(!count($err))
{
  $_POST['logusername'] = mysql_real_escape_string($_POST['logusername']);
  $_POST['password'] = mysql_real_escape_string($_POST['password']);
  $_POST['rememberMe'] = (int)$_POST['rememberMe'];
 
  // Escaping all input data
  $row = mysql_fetch_assoc(mysql_query("SELECT * FROM playerdata WHERE user='{$_POST['logusername']}' AND password='".sha1($_POST['password'])."'"));
  if($row['user'])
  {
   // If everything is OK login
  
   $_SESSION['user'] = $row['user'];
   $_SESSION['id'] = $row['id'];
   $_SESSION['rememberMe'] = $_POST['rememberMe'];
  
   // Store some data in the session
  
   setcookie('tzRemember',$_POST['rememberMe']);
  }
  else $err[]='You have entered an invalid username or password.';
}

if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: http://127.0.0.1/");
exit;
}
else if($_POST['submit']=='Register')
{
// If the Register form has been submitted
$err = array();

if (!preg_match('/^[A-Za-z]{4,9}_{1}[A-Za-z]{4,9}$/', $_POST['username']))
{
  $err[] = 'Your username must be in the format of "John_Smith" (include the underscore) with a maximum of 19 characters and a minimum of 9. No other special characters are allowed.';
}

$email = $_POST['email'];
$query = sprintf("SELECT * FROM playerdata WHERE email='%s'", mysql_real_escape_string($email));
$result = mysql_query($query);
if(!$result)
{
	 $err[]='There has been an error with your connection, please refresh the page and try again.';
}
else
{
  if(mysql_num_rows($result) > 0)
  {
		  $err[]='That email address already exists.';
	 }
}

if(!checkEmail($_POST['email']))
{
  $err[]='Your email address is not valid.';
}

if(!count($err))
{
  // If there are no errors
 
  $pass = substr(sha1($_SERVER['REMOTE_ADDR'].microtime().rand(1,100000).rand(170000,200000)),0,6);
  // Generate a random password
 
  $_POST['email'] = mysql_real_escape_string($_POST['email']);
  $_POST['username'] = mysql_real_escape_string($_POST['username']);
  // Escape the input data
 
 
  mysql_query(" INSERT INTO playerdata(user,password,level,money,email,ip,datetime)
	  VALUES(
	 
	   '".$_POST['username']."',
	   '".sha1($pass)."',
	   '1',
	   '20',
	   '".$_POST['email']."',
	   '".$_SERVER['REMOTE_ADDR']."',
	   NOW()
	  
	  )");
 
  if(mysql_affected_rows($link)== 1)
  {
   send_mail( 'bugsyccfc@googlemail.com',
	  $_POST['email'],
	  'Welcome to Domination Roleplay.',
	  'Your password is: '.$pass);
   $_SESSION['msg']['reg-success']='An email has been sent containing your password. '.$pass;
  }
  else $err[]='That username has already been taken.';
}
if(count($err))
{
  $_SESSION['msg']['reg-err'] = implode('<br />',$err);
}

header("Location: http://127.0.0.1/");
exit;
}
else if($_POST['submit']=='Confirm') // [size=4][b]Change Pass Starts Here[/b][/size]
{

$err = array();
// Will hold our errors


if(!$_POST['password2'] || !$_POST['password3'])
  $err[] = 'All fields are required.';
header("Location: http://127.0.0.1/");
exit;
}  // [size=4][b]Change Pass Ends Here[/b][/size] (No idea what to do now) [b]Change pass form is below[/b]
$script = '';
if($_SESSION['msg'])
{
// The script below shows the sliding panel on page load

$script = '
<script type="text/javascript">

  $(function(){
 
   $("div#panel").show();
   $("#toggle a").toggle();
  });

</script>';

}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Domination Roleplay UCP - Home</title>
<!-- CCS Links -->
  <link rel="stylesheet" type="text/css" href="data/css/register.css" media="screen" />
  <link rel="stylesheet" type="text/css" href="data/css/slide.css" media="screen" />
<!-- End of CCS Links -->
<!-- Javascript Links -->  
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <!-- PNG FIX for IE6 -->
    <!-- http://24ways.org/2007/supersleight-transparent-png-in-ie6 -->
    <!--[if lte IE 6]>
	    <script type="text/javascript" src="http://127.0.0.1/data/js/supersleight-min.js"></script>
    <![endif]-->
   
    <script src="data/js/slide.js" type="text/javascript"></script>
   
    <?php echo $script; ?>
<!-- End of Javascript Links -->
</head>
<!-- Login/Register UCP -->
<div id="toppanel">
<div id="panel">
  <div class="content clearfix">
   <div class="left">
    <h1>The Sliding jQuery Panel</h1>
    <h2>A register/login solution</h2> 
    <p class="grey">You are free to use this login and registration system in you sites!</p>
    <h2>A Big Thanks</h2>
    <p class="grey">This tutorial was built on top of <a href="http://web-kreation.com/index.php/tutorials/nice-clean-sliding-login-panel-built-with-jquery" title="Go to site">Web-Kreation</a>'s amazing sliding panel.</p>
   </div>
		   
		   
		    <?php
  
   if(!$_SESSION['id']):
  
   ?>
		   
   <div class="left">
    <!-- Login Form -->
    <form class="clearfix" action="" method="post">
	 <h1>Member Login</h1>
				   
				    <?php
	 
	  if($_SESSION['msg']['login-err'])
	  {
	   echo '<div class="err">'.$_SESSION['msg']['login-err'].'</div>';
	   unset($_SESSION['msg']['login-err']);
	  }
	 ?>
	
	 <label class="grey" for="username">Username:</label>
	 <input class="field" type="text" name="logusername" id="logusername" value="" size="23" maxlength="19" />
	 <label class="grey" for="password">Password:</label>
	 <input class="field" type="password" name="password" id="password" size="23" maxlength="13" />
			  <label><input name="rememberMe" id="rememberMe" type="checkbox" checked="checked" value="1" /> &nbsp;Remember me</label>
		   <div class="clear"></div>
	 <input type="submit" name="submit" value="Login" class="bt_login" />
    </form>
   </div>
   <div class="left right">  
    <!-- Register Form -->
    <form action="" method="post">
	 <h1>Not a member yet? Sign Up!</h1> 
				   
				    <?php
	 
	  if($_SESSION['msg']['reg-err'])
	  {
	   echo '<div class="err">'.$_SESSION['msg']['reg-err'].'</div>';
	   unset($_SESSION['msg']['reg-err']);
	  }
	 
	  if($_SESSION['msg']['reg-success'])
	  {
	   echo '<div class="success">'.$_SESSION['msg']['reg-success'].'</div>';
	   unset($_SESSION['msg']['reg-success']);
	  }
	 ?>
					 
	 <label class="grey" for="username">Username:</label>
	 <input class="field" type="text" name="username" id="username" value="" size="23"maxlength="19" />
	 <label class="grey" for="email">Email:</label>
	 <input class="field" type="text" name="email" id="email" size="23" />
	 <label>A password will be sent to your email address provided.</label>
	 <input type="submit" name="submit" value="Register" class="bt_register" />
    </form>
   </div>
		   
		    <?php
  
   else:
  
   ?>
		   
		    <div class="left">
		    <?php
   $query = sprintf("SELECT * FROM `playerdata` WHERE `user` = '%s'", mysql_real_escape_string($_SESSION['user']));
   $result = mysql_query($query)or die(mysql_error());
   echo '<h1><b><font color="#FFFFFF">'.$_SESSION['user'].'s User Control Panel</font></h1></b>';
		    echo '<p><b><font color="#FF0000">IP Address</font>: <font color="#FFFFFF">'.$_SERVER['REMOTE_ADDR'].'</font></p></b>';
   while($row = mysql_fetch_array($result))
	 {
    echo '<p><b><font color="#FF0000">Registered</font>: <font color="#FFFFFF">'.$row['datetime'].'</font></p></b>';
	  echo '<p><b><font color="#FF0000">Cash</font>: <font color="#009933">$'.$row['money'].'</font></p></b>';
	  echo '<p><b><font color="#FF0000">Level</font>: <font color="#FFFFFF">'.$row['level'].'</font></p></b>';
	 }
		    ?>
		    <a href="?logoff">Log Out</a>
		    </div>
		   
		    <div class="left right">
   <h1>Your Account Settings</h1>
		    <?php
		    echo '<h2><font color="#FFFFFF">Change Password</font></h2>' [b][size=4]// Change Pass Form[/size][/b]
   ?>
		    <form action="" method="post"><br />					  
   <label class="grey" for="password">Existing Password:</label>
   <input class="field" type="password" name="password2" id="password2" size="23" maxlength="13" />
   <label class="grey" for="password">New Password:</label>
   <input class="field" type="password" name="password3" id="password3" size="23" maxlength="13" />
   <label class="grey" for="password">Confirm Password:</label>
   <input class="field" type="password" name="password4" id="password4" size="23" maxlength="13" />
		    <input type="submit" name="submit" value="Confirm" class="bt_changepass" />
		    </div>
		   
		    <?php
   endif;
   ?>
  </div>
</div> <!-- /login -->
    <!-- The tab on top -->
<div class="tab">
  <ul class="login">
	  <li class="left">&nbsp;</li>
		 <li>Welcome <?php echo $_SESSION['user'] ? $_SESSION['user'] : 'Guest';?>!</li>
   <li class="sep">|</li>
   <li id="toggle">
    <a id="open" class="open" href="#"><?php echo $_SESSION['id']?'Open Panel':'Log In | Register';?></a>
    <a id="close" style="display: none;" class="close" href="#">Close Panel</a>  
   </li>
	  <li class="right">&nbsp;</li>
  </ul>
</div> <!-- / top -->

</div> <!--Login/Register UCP -->
</body>
</html>

Thanks a lot for taking your time to help!

#2 Aphex

Aphex

    Newbie

  • New Members
  • Pip
  • 6 posts

Posted 22 January 2013 - 12:07 PM

Anyone able to help here?

#3 Jessica

Jessica

    This is not my name.

  • Gurus
  • 8,982 posts
  • LocationDallas, TX
  • Age:26

Posted 22 January 2013 - 12:57 PM

Since you haven't asked a question about a specific problem, this looks more like peer-review request, so I'm moving this to critiques.
My goal in replying to posts is to help you become a better programmer, including learning how to debug your own code and research problems. For that reason, rather than posting the solution, I reply with tips and hints on how to find the solution yourself. See below for useful links when you get stuck.

How to Get Good Help: How to Ask Questions | Don't be a help vampire
Debugging Your Code: Debugging your SQL | What does a php function do? | What does a term mean? | Don't see any errors?
Things You Should Do: Normalize Your Data | use print_r() or var_dump()
Lulz: "Functions should not have side effects." - trq

Please take a look at my new PHP/Web Dev blog: The Web Mason - Thanks!!

#4 davidannis

davidannis

    Freak Dr.

  • Members
  • PipPipPip
  • 457 posts
  • LocationOkemos, MI USA

Posted 03 March 2013 - 08:23 PM


 

if(!$_POST['password2'] || !$_POST['password3'])// need to check password 4 here too
{
$err[] = 'All fields are required.';
header("Location: http://127.0.0.1/");// you need to do something witht he error message or they just get redirected and don't know why.
exit;}

}
//ok - all fields are here 
$row = mysql_fetch_assoc(mysql_query("SELECT * FROM playerdata WHERE user='{$_POST['logusername']}' AND password='".sha1($_POST['password2'])."'")); 
// see that they were right about existing password
// you can check affected rows as you did above
if ($_POST['password3']==$_POST['password4']){
see that both new passwords match
$query="UPDATE playerdata SET password='".sha1($_POST['password3'])."' WHERE USER=//...update the password (finish this query and then execute it.
}else{
$err[]='error new passwords don't match';
}

 // [size=4][b]Change Pass Ends Here[/b][/size] (No idea what to do now) 

I would also suggest salting the passwords (adding some characters to the begining and end before using the sha1 on them.



#5 Christian F.

Christian F.

    Advanced Member

  • Staff Alumni
  • 3,106 posts
  • LocationNorway

Posted 06 March 2013 - 10:02 AM

I recommend watching this video:


Then read this article:
http://www.openwall....Users-Passwords

And, finally, rewrite the login system using what you just learned to make it secure.
Keeping it simple.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com