Location: PHPKode > scripts > phpEmailUser > login_reg_change.php
<?php

/* phpemailuser by georgfly */

session_start();
if(@$_SESSION['auth'] != "yes")
{
	header("Location: login_reg.php");
	exit();
}


include("config.inc.php");
include("login_reg_functions.php");

// MAKE CHANGES IN DB

if (isset($_POST['Button'])){
if ($_POST['Button'] == "Save Changes"){


foreach($_POST as $field => $value){
	// check if this is one of our specified fields (excludes buttons, passwordrep)
	if (isset($fieldnames[$field]))
	{
		if ($field != 'password')
			$strippedpost[$field] = strip_tags(trim($value));
		else $strippedpost[$field] = trim($value);
		if ($fieldnames[$field][2] == "yes" && $field != 'password')
		{
				if (empty($value))
				{
					$blanks[] = $fieldnames[$field][0];
				}
		}
	}
} // end foreach POST

if(isset($blanks))
{
	$message_2 = "The following fields are blank.
	Please enter the required information: ";
	foreach($blanks as $value)
	{
		$message_2 .="$value, ";
	}
	$message_2 = trim ($message_2, ', ');
	goto exitupdate;
} // end if blanks found


/* validate data = sanitize with preg_match */
foreach($strippedpost as $field => $value){
	if(!empty($value)){
		if (!preg_match($fieldnames[$field][3], $value)){
			$errors[] = "$value is not a valid entry for ".$fieldnames[$field][0];
		}
		elseif ($field == "user_email"){
			if (!isValidEmail($value)){
				$errors[] = "$value is not a valid entry for ".$fieldnames[$field][0];
			}
		}
	} // end if not empty
} // end foreach POST



if(@is_array($errors))
{
	$message_2 = "";
	foreach($errors as $value)
	{
		$message_2 .= $value."<br>";
	}
	goto exitupdate;
} // end if errors are found


/* check if new user_email already exists */
$cxn = mysqli_connect($mysqlhost,$mysqluser,$mysqlpass,$mysqldb)
or die("Couldn't connect to server");
if ($strippedpost['user_email'] != $_SESSION['logname']) // a new email address?
{
	$sql = "SELECT user_email FROM user
	WHERE user_email='".mysqli_real_escape_string($cxn,$strippedpost['user_email'])."'";
	$result = mysqli_query($cxn,$sql)
	or die("Query died: user_email.");
	$num = mysqli_num_rows($result);
	if($num > 0)
	{
		$message_2 = "$strippedpost[user_email] is already registered";
		goto exitupdate;
	} // end if user email already exists
// no new email address => need no activation!
} else {
$needactivation = false; }


// check password
$newpassword = trim(@$_POST['newpassword']);
$newpasswordrep = trim(@$_POST['newpasswordrep']);
if (empty($strippedpost['password']) && empty($newpassword)){
	unset($strippedpost['password']);
} elseif (empty($strippedpost['password']) && !empty($newpassword)){
	$message_2 = "To change your password you need to enter the old password.";
	goto exitupdate;
} elseif (!empty($strippedpost['password']) && empty($newpassword)) {
	$message_2 = " To change your password you need to enter a new password.";
	goto exitupdate;
} elseif ($newpassword != $newpasswordrep) {
	$message_2 = "The entries for the new password don't match.";
	goto exitupdate;
} elseif (strlen($newpassword) < $minpasslen) {
	$message_2 = "The new password has to be at least $minpasslen characters long.";
	goto exitupdate;
} else { // the passwords seems ok
	// finally we need to check if the old password is the correct one!
	$sql = "select password from user where uid=".$_SESSION['uid'];
	$result = mysqli_query($cxn,$sql)
	or die("Query died: password.");
	$row = mysqli_fetch_assoc($result);
	if (md5($strippedpost['password']) != $row['password']) {
		$message_2 = "The old password you entered is incorrect.";
		goto exitupdate;
	} else {
		$strippedpost['password'] = $newpassword;
	}
}

// update data in database
// first in db user
$uid = $_SESSION['uid'];
$today = date("Y-m-d H:i:s");
$actkey = md5(randomword(10) . time());
$activated = abs($needactivation-1);
$actkeyprev = md5(randomword(10) . time());
$tablecols = mysqli_get_colnames($cxn,'user'); 
$sql = "";
foreach($strippedpost as $field => $value){
	foreach($tablecols as $col){
		if ($field == $col){
			if ($field == "password"){
				$sql .= "$field = md5('$value'),";
			} else {
				$sql .= "$field='".mysqli_real_escape_string($cxn,$value)."',";
			}
			break;
		}
	}
}
if ($needactivation){
	$sql = "UPDATE user set ".$sql."prevemail='".$_SESSION['logname']."',actkeyprev='$actkeyprev',activated=0,actkey='$actkey',actkey_date='$today' where uid = $uid";
} else {
	$sql = "UPDATE user set ".$sql."prevemail='".$_SESSION['logname']."',actkey_date='$today' where uid = $uid";
}
$result = mysqli_query($cxn,$sql)
or die ("Query died: insert data into user.");

// and now insert data into db userdata
$tablecols2 = mysqli_get_colnames($cxn,'userdata'); 
$sql = "";
foreach($strippedpost as $field => $value){
	foreach($tablecols2 as $col){
		if ($field == $col){
			if ($field == "password"){
				$sql .= "$field = md5('$value'),";
			} else {
				$sql .= "$field='".mysqli_real_escape_string($cxn,$value)."',";
			}
			break;
		}
	}
}
$sql = trim($sql,",");
if (!empty($sql)){
	$sql = "UPDATE userdata set ".$sql." where uid = $uid";
	$result = mysqli_query($cxn,$sql)
	or die ("Query died: insert data into userdata.");
}

/* send email to user */
if ($strippedpost['user_email'] != $_SESSION['logname']){
	$emess = "You have changed your registered email address.<br>\n";
	$emess .= "The new email address is ".$strippedpost['user_email'].".";
	if ($needactivation){
		$emess .= "<br><br>\n\nYou still need to re-activate your account: 
		<a href=\"$dirurl/login_reg_act.php?ak=$actkey&ud=$uid\">CLICK THIS LINK</a><br>\n";
		$emess .= "or paste this link into your browser's address bar:<br>$dirurl/login_reg_act.php?ak=$actkey&ud=$uid<br>";
		$emess .= "This link expires after $activationkeyexpire hours.";
	}
	//$emess .= "Your password is:<br>\n";
	//$emess .= "$strippedpost[password]<br><br>\n\n";
	$subj = "New registered email address at $sitename";
	$headers = "From: $sitename <$sendfromemail>\r\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; 
	mail($strippedpost['user_email'], $subj, $emess, $headers);
	$emess = "You have changed your registered email address.<br>\n";
	$emess .= "The new email address is ".$strippedpost['user_email'].".";
	if ($needactivation){
		$emess .= "<br><br>\n\nYou can undo this change (and keep the registered email address ".$_SESSION['logname'].") by clicking ";
		$emess .= "<a href=\"$dirurl/login_reg_act.php?ak=$actkeyprev&ud=$uid&action=undo\">THIS LINK</a>.<br>\n";
		$emess .= "You can also paste this link into your browser's address bar:<br>$dirurl/login_reg_act.php?ak=$actkeyprev&ud=$uid&action=undo<br>\n";
		$emess .= "This link expires after $activationkeyexpire hours.";
	}
	mail($_SESSION['logname'], $subj, $emess, $headers);
	if ($needactivation){
		session_destroy();
		?>
		<html><head><title>Email address change</title>
		</head>
		<body>
		<?php
		echo "We have sent you an email to your new email address ".$strippedpost['user_email']." containing a link to re-activate your accout.<br>";
		echo "We have also sent you an email to your old address ".$_SESSION['logname']." with a link to undo this change.<br>";
		echo "The links expire after $activationkeyexpire hours.<br>";
		echo "<a href=\"$dirurl/login_reg.php\">Please click here to log in.</a>";
		?>
		</body></html>
		<?php
		exit;
	}
}
$message_2="Your account has been successfully updated.";

$_SESSION['logname'] = $strippedpost['user_email'];

}
}


exitupdate:

// NOW WE DRAW THE FORM WITH DATA FROM DB

// first we check which fields are to be changed:
// we also have to query table userdata:
// if we have multiple or zero addresses in userdata table, we only display fields from table user; adresses would have to be changed / added in a separate interface
if (!isset($cxn)){
	$cxn = mysqli_connect($mysqlhost,$mysqluser,$mysqlpass,$mysqldb)
	or die("Query died: connect");
}
$tablecols2 = mysqli_get_colnames($cxn,'userdata');
if ($addrchange_disp){
	$sql = "select * from userdata where uid = ".$_SESSION['uid'];
	$result = mysqli_query($cxn,$sql)
	or die("Query died: userdata");
	$num = mysqli_num_rows($result);
	if ($num <> 1) {
		$addrchange_disp = false;
	} else {
		$row = mysqli_fetch_assoc($result);
	}
}
// now get data from table user
$sql = "select * from user where uid = ".$_SESSION['uid'];
$result2 = mysqli_query($cxn,$sql)
or die("Query died: user");
$row2 = mysqli_fetch_assoc($result2);

$fields_change = array();
foreach ($fieldnames as $key => $value)
{
	if ($value[1] == "yes")
	{
		// check if this is an addressfield
		$skipfield = false;
		$isaddressfield = false;
		foreach ($tablecols2 as $col){
			if ($col == $key){
				if (!$addrchange_disp){
					$skipfield = true;
				} else {
					$isaddressfield = true;
					$currentvalue = $row[$key];
				}
				break;
			}
		}
		if ($skipfield) continue;
		
		// if not $isaddressfield, we have to get currentvalue from table user ($result2)
		if (!$isaddressfield){
			$currentvalue = $row2[$key];
		}
		
		// now copy data (field display name, current value in database, textfield or password?, isaddressfield?) into $fields_change
		$fields_change[$key] = array($value[0],$currentvalue,"text",$isaddressfield);
		if ($value[2] == "yes")
		{
			if ($key == "password")
				$fields_change[$key][0] = "Old Password (leave empty for no change)";
			else
				$fields_change[$key][0] .= "<font color='red'>*</font>";
		}
		if ($key == "password")
		{
			$fields_change["password"][1] = "";
			$fields_change["password"][2] = "password"; // field type
			$fields_change["newpassword"] = array("New ".$value[0],"","password",false);
			$fields_change["newpasswordrep"] = array("Repeat new ".$value[0],"","password",false);
		}
	}
}
?>



<!-- display the form -->

<html><head><title>Change User Data Page</title>
<style type='text/css'>
<!--
label {
font-size: 85%;
float: left;
width: 35%;
margin-right: .5em;
text-align: right;
clear:left;
}
legend {
font-weight: bold;
font-size: 1em;
margin-bottom: .5em;
}
#wrapper {
margin: 0;
padding: 0;
}
#reg {
position: absolute;
left: 0;
width: 450px;
padding: 1em 0;
}

#field {padding-bottom: .5em;}
.errors {
font-weight: bold;
font-style: italic;
font-size: 90%;
color: red;
margin-top: 0;
}
-->
</style>
</head>
<body style="margin: 0">
	



<div id="reg">
<form action=<?php echo $_SERVER['PHP_SELF'].' '?> method="POST">
<fieldset style='border: 1px solid #000000'>
<legend>Change your account data</legend>

<?php
if(isset($message_2))
	echo "<p class='errors'>$message_2</p>\n";

foreach($fields_change as $field => $valuearray)
{
	echo "<div id='field'>
	<label for='$field'>$valuearray[0]</label>
	<input id='$field' name='$field' type=$valuearray[2] ";
	if ($field=="password" || $field=="newpassword" || $field=="newpasswordrep"){
		echo " style='background-color: #F0F0F0;'";
	}
	echo "value='$valuearray[1]' size='30' maxlength='50' />
	</div>\n";
} // end foreach field

?>

<input type="submit" name="Button"
style='margin-left: 45%; margin-bottom: .5em'
value="Save Changes">
</fieldset>
</form>
</div>
</div>
</body></html>
Return current item: phpEmailUser