So im trying to have a user update their profile from update.php and then display it in userprofile.php but I am getting the error :"Cannot update: Duplicate entry 'username' for key 1". Ive tried to find a solution but im pretty stuck. Any help would be appreciated.
Here is update.php
<!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>
<title>User Profile Update</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<?php
session_start();
if(!isset($_SESSION['logged']) || $_SESSION['logged'] = TRUE)
{
$userError = "Error! Invalid Username.";
$passError = "Error! Invalid Password.";
$emailError = "Error! Invalid Email.";
$conError = "Error! Passwords do not match.";
$errorCheck = false;
$regex = '/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}#)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*#(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD';
if (isset($_POST['update']))
{
if(empty($_POST["firstName"])){
echo $userError;
$errorCheck = True;
}
elseif(empty($_POST["lastName"])){
echo $passError;
$errorCheck = True;
}
elseif(empty($_POST["userName"])){
echo $userError;
$errorCheck = True;
}
elseif(empty($_POST["pass"])){
echo $passError;
$errorCheck = True;
}
elseif(preg_match($regex, $_POST["email"]) != 1) {
echo $emailError;
$errorCheck = True;
}
elseif($_POST["pass"] != $_POST["pass2"]){
echo $conError;
$errorCheck = True;
}
elseif($_POST["address"] != $_POST["address"]){
echo $conError;
$errorCheck = True;
}
if(isset($_POST['update']) && (!$errorCheck)){
$user="bparis";
$pass="soccerguy998";
$database="bparis";
$passwordSub=$_POST["pass"];
$encrypted_mypassword=md5($passwordSub);
$con=mysql_connect("localhost", $user, $pass)
or die ('Couldnt connect to server');
mysql_select_db($database,$con)
or die('could not connect to db');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$key_id = $_POST["userName"];
$key_id2 = $_POST["email"];
//$location = $_POST['location'];
update($key_id2);
}else
{
userupdate();}
}else
{userupdate();}
}else
{ //if no user is logged in, display error
echo "<h1>Access denied</h1>";
echo "<h3><a href=login.php>Click here to login</a></h3>";
}
?>
<?php
function update($email){
$_SESSION['email'] = $email;
$sQry = "SELECT email FROM members WHERE email = " . (int)$_SESSION['email']; // Int userid
$obQry = mysql_query($sQry) or die(mysql_error()); // Shortcut, bad but usable
if (mysql_num_rows($obQry) == 1)
{
// Single record exists:// EDIT USER_PROFILE
$sReplace = "UPDATE members (username,password,email,firstName,lastName,address) VALUES('$_POST[userName]','$encrypted_mypassword','$_POST[email]','$_POST[firstName]','$_POST[lastName]','$_POST[address]')";
// Remember, I assumed that email is an integer!
}
else
{
$passwordSub=$_POST["pass"];
$encrypted_mypassword=md5($passwordSub);
$sReplace = "INSERT INTO members (username,password,email,firstName,lastName,address) VALUES('$_POST[userName]','$encrypted_mypassword','$_POST[email]','$_POST[firstName]','$_POST[lastName]','$_POST[address]')";
}
$obUpdate = mysql_query($sReplace) or die('Cannot update: ' . mysql_error());
if($obUpdate){
$subject = "Profile updated ";
$message = "You have updated your profile with Belfort Furniture. If not please contact customer service at : 703-406-7600";
$Belfortemail = "akomala.akouete#belfortfurniture.com";
echo "<b>profile updated</b>";mail($email, $subject,$message, "From:" . $Belfortemail);}else{
echo "Try update again";}
}
?>
<?php
function userupdate(){
?>
<table>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<h1>Profile Update</h1>
<hr>
<tr><td>First Name:</td><td>
<input type="text" name="firstName" maxlength="20">
</td></tr>
<tr><td>Last Name:</td><td>
<input type="text" name="lastName" maxlength="20">
</td></tr>
<tr><td>Username:</td><td>
<input type="text" name="userName" maxlength="20">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="pass" maxlength="20">
</td></tr>
<tr><td>Confirm Password:</td><td>
<input type="password" name="pass2" maxlength="20">
</td></tr>
<tr><td>Email:</td><td>
<input type="text" name="email" maxlength="50">
</td></tr>
<tr><td>Address:</td><td>
<input type="text" name="address" maxlength="100">
</td></tr>
<!--<tr>
<td class="right">address 1: </td>
<td><input type="text" name="location" value="" size="60" /></td>
</tr>-->
<tr><th colspan=2><input type="submit" name="update" value="UPDATE"></th></tr>
</form>
</table>
<?php
echo "<br><h3><a href=usersProfile.php>View your profile</a></h3>";
}
?>
</body>
</html>
and here is userprofile.php
<?php
session_start();
# DB INFO #
$user="xxxx";
$pass="xxxxx";
$database="xxxxx";
$con=mysql_connect("localhost", $user, $pass)
or die ('Couldnt connect to server');
mysql_select_db($database,$con)
or die('could not connect to db');
$result = mysql_query("SELECT userName,email,firstName,lastName,address FROM members") or die(mysql_error());
showpUsers($result);
function showpUsers($result)
{
?>
<table border="1">
<tr>
<?php
$headings = array("Usernam","Email","First Name","Last Name","Address");
foreach($headings as $info) {
echo "<th border='1'>" . $info . "</th>";
}
?>
</tr>
<?php
if(count($result)>0){
$list = array("username","email","firstName","lastName","address");
//while($data = mysql_fetch_row($result)){
$data = $result;
echo "<tr border='1'>";
for($i=0;$i<count($data);$i++) {
echo "<td border='1'>" . $data[$i] . "</td>";
}
echo "</tr>";
//}
}else{
echo "<b>Empty users list</b>";
}
?>
</table>
<?php
}
echo "<a href=update.php><button type='button'>USER UPDATE</button> </h1>";
?>
<hr/>
<br/>
<h3>Return Home Page</h3>
There are two situations I can see that might cause this:
You have two or more rows in the database with the same username, and your INSERT statement is being called. Check for this explicitly by only calling this block if the number of rows returned was 0. At the moment you aren't testing for it at all.
Your username is the PRIMARY KEY for the table. In this case you should alter your table so that it has a unique auto_incrementing primary key.
Oh, and rewrite the whole thing to fix the massive SQL injection vulnerabilities. Don't let this code anywhere near a public web site in the state it's in.
Related
wait please, dont post this as a duplicate because ive done research and tried everything but cant get it to work, i keep getting this error "Fatal error: Call to a member function prepare() on string in C:\wamp64\www\Etego\dbcontroller.php on line 63" i am trying to get people on my inscription form not to use the same email twice, thanks in advance! heres the code :
dbcontroller.php
<?php
class DBController {
public $host = "localhost";
public $user = "root";
public $password = "";
public $database = "members";
public $conn;
function __construct() {
$this->conn = $this->connectDB();
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
return $conn;
}
function runQuery($query) {
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
function numRows($query) {
$result = mysqli_query($this->conn,$query);
$rowcount = mysqli_num_rows($result);
return $rowcount;
}
function updateQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query1: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function insertQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query2: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function deleteQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query3: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
}
/* Email already exists */
/*line 63*/
$db = new DBController;
$db->database->prepare("SELECT * FROM members WHERE email = ?");
$reqemail->execute(array($email));
$emailexist = $reqemail->rowCount();
if($emailexist == 0) {
} else {
$error_message = "Email already exists";
}
//end of email existance
?>
index2.php
<!-- how to make members when login "keep me signed in" and ho to make users 13+ with the date input -->
<?php
if(!empty($_POST["register-user"])) {
/* Form Required Field Validation */
foreach($_POST as $key=>$value) {
if(empty($_POST[$key])) {
$error_message = "All Fields are required";
break;
}
}
/* Password Matching Validation */
if($_POST['password'] != $_POST['confirm_password']){
$error_message = 'Passwords should be same<br>';
}
/* Email Validation */
if(!isset($error_message)) {
if (!filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL)) {
$error_message = "Invalid Email Address";
}
}
/* Validation to check if gender is selected */
if(!isset($error_message)) {
if(!isset($_POST["gender"])) {
$error_message = " All Fields are required";
}
}
/* Validation to check if Terms and Conditions are accepted */
if(!isset($error_message)) {
if(!isset($_POST["terms"])) {
$error_message = "Accept Terms and Conditions to Register";
}
}
if(!isset($error_message)) {
require_once("dbcontroller.php");
$db_handle = new DBController();
$query = "INSERT INTO members (username, firstname, lastname, password, email, gender, dob) VALUES
('" . $_POST["userName"] . "', '" . $_POST["firstName"] . "', '" . $_POST["lastName"] . "', '" . md5($_POST["password"]) . "', '" . $_POST["userEmail"] . "', '" . $_POST["gender"] . "' , '" . $_POST["dob"] . "' )";
$result = $db_handle->insertQuery($query);
if(!empty($result)) {
$error_message = "";
$success_message = "You have registered successfully!";
unset($_POST);
} else {
$error_message = "Problem in registration. Try Again!";
}
}
}
?>
<html>
<?php
include 'C:\wamp64\www\Etego\stylesignup.css';
?>
<head>
<title>https://Etego/signup.com</title>
</head>
<body>
<form name="frmRegistration" method="post" action="">
<table border="0" width="500" align="center" class="demo-table">
<?php if(!empty($success_message)) { ?>
<div class="success-message"><?php if(isset($success_message)) echo $success_message; ?></div>
<?php } ?>
<?php if(!empty($error_message)) { ?>
<div class="error-message"><?php if(isset($error_message)) echo $error_message; ?></div>
<?php } ?>
<tr>
<td>User Name</td>
<td><input type="text" class="demoInputBox allinsc" name="userName" value="<?php if(isset($_POST['userName'])) echo $_POST['userName']; ?>"></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" class="demoInputBox allinsc" name="firstName" value="<?php if(isset($_POST['firstName'])) echo $_POST['firstName']; ?>"></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" class="demoInputBox allinsc" name="lastName" value="<?php if(isset($_POST['lastName'])) echo $_POST['lastName']; ?>"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" class="demoInputBox allinsc" name="password" value=""></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="password" class="demoInputBox allinsc" name="confirm_password" value=""></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" class="demoInputBox allinsc" name="userEmail" value="<?php if(isset($_POST['userEmail'])) echo $_POST['userEmail']; ?>"></td>
</tr>
<tr>
<td>Date Of birth</td>
<td><input type="date" value="<?php print(date("YYYY-MM-DD"))?>" class="demoInputBox" name="dob" value="<?php if(isset($_POST['dob'])) echo $_POST['dob']; ?>"></td>
</tr>
<tr>
<td>Gender</td>
<td><input type="radio" name="gender" value="Male" <?php if(isset($_POST['gender']) && $_POST['gender']=="Male") { ?>checked<?php } ?>> Male
<input type="radio" name="gender" value="Female" <?php if(isset($_POST['gender']) && $_POST['gender']=="Female") { ?>checked<?php } ?>> Female
<input type="radio" name="gender" value="not specified" <?php if(isset($_POST['gender']) && $_POST['gender']=="not specified") { ?>checked<?php } ?>> not specified
</td>
</tr>
<tr>
<td colspan=2>
<input type="checkbox" name="terms"> I accept Terms and Conditions <input type="submit" name="register-user" value="Register" class="btnRegister"></td>
</tr>
</table>
</form>
<div class="header1"></div>
<div class="hdetail1"></div>
<h class="etegotxt1">Etego</h>
<img src="Etego_Logo.png" alt="Etego logo" width="50" height="50" class="logo1">
</body></html>
There are a number of issues here:
Where you are trying to prepare a statement you are using $db->database->prepare() and if you look at your class the propery database it is a String containing the string members i.e. public $database = "members"; Which explains the error that is being reported
You also appear to have got the mysqli_ API and the PDO API confused and are using some PDO API functions, that will never work they are totally different beasts.
So also change this
/* Email already exists */
/*line 63*/
$db = new DBController;
$db->database->prepare("SELECT * FROM members WHERE email = ?");
$reqemail->execute(array($email));
$emailexist = $reqemail->rowCount();
if($emailexist == 0) {
} else {
$error_message = "Email already exists";
}
To
/* Email already exists */
/*line 63*/
$db = new DBController;
$stmt = $db->conn->prepare("SELECT * FROM members WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0) {
$error_message = "Email already exists";
}
and you will be using the connection object to prepare the query and all mysqli_ API functions, methods and properties.
UPDATE: Still getting dup accounts created
Your dup account check is in the wrong place in my opinion and should be moved into the index2.php.
Or after this line add a test against $error_message because you are forgetting to test if the Dup email check produced an error.
if(!isset($error_message)) {
require_once("dbcontroller.php");
if ( !isset($error_message) ) {
My strong suggestion would be to do the Dup Email check in index2 and remove it from dbconnect.php as it does not really belong in dbconnect.php as that would be run unnecessarily everytime you want to connect to a database in any script!
The thing is your $database variable is a string that does not have prepare() function. Instead you might want to use the $conn variable that is holding a valid database connection.
To do that, change
$db->database->prepare("SELECT * FROM members WHERE email = ?");
to
$stmt = $db->conn->prepare("SELECT * FROM members WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
Here is the PHP official documentation.
I am trying to make a writing board and need to save ID value in the DB when the writer done its saving.
But my db shows only '0' member_idx and it looks my id session maintating is now working.
I attach related code of mine, but please let me know if you need more codes which I've missed.
_this is my work_tree under htdocs of apache2
enter image description here
this is login_check.php
<?php
session_start();
include_once ('../config.php');
$mysqli = new mysqli($DB['host'], $DB['id'], $DB['pw'], $DB['db']);
if (mysqli_connect_error()) {
exit('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
}
extract($_POST);
$q = "SELECT * FROM ap_member WHERE id='$user_id'";
$result = $mysqli->query($q);
if($result->num_rows==1) {
$encrypted_pass = sha1($user_pass);
$row = $result->fetch_array(MYSQLI_ASSOC);
if( $row['pw'] == $encrypted_pass ) {
$_SESSION['member_idx'] = $row['member_idx'];
header('Location: '.$url['root'].'login_done.php');
}
else {
echo 'wrong password';
}
}
else {
echo 'ID does not exist or invalid approach. Try again.';
}
if( $row['pw'] == $encrypted_pass ) {
$_SESSION['is_logged'] = 'YES';
$_SESSION['user_id'] = $user_id;
$_SESSION['member_idx'] = $row['member_idx'];
header('Location: '.$url['root'].'login_done.php');
exit();
}
else {
$_SESSION['is_logged'] = 'NO';
$_SESSION['user_id'] = '';
header('Location: '.$url['root'].'login_done.php');
exit();
}
?>
_this is write.php
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/preset.php';
include $_SERVER['DOCUMENT_ROOT'].'/header.php';
?>
Write a Commment for anything please <br />
<form name ="write_form" method = "POST" action = "./write_check.php">
<input type="hidden" name="member_idx" value="<?php echo $_SESSION['member_idx'] ?>">
<table>
<tr>
<td>
Title
</td>
<td>
<input type ="text" name = "subject" size ="90">
</td>
</tr>
<tr>
<td>
Content
</td>
<td>
<textarea name="content" cols="100" rows="10"></textarea>
</td>
</tr>
</table>
<div>
<input type = "submit" value = "저장">
</div>
</form>
<?php
include $_SERVER['DOCUMENT_ROOT'].'/footer.php';
?>
_ and finally this is my DB what it looks like now
_+ here's my ap_bbs
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/preset.php';
?>
<?php
$reg_date = time();
$member_idx = $_SESSION['member_idx'];
$q = "INSERT INTO ap_bbs (member_idx, subject,content,reg_date) VALUES('$member_idx', '$subject', '$content', '$reg_date')";
$result = $mysqli->query($q);
if ($result==false) {
$_SESSION['writing_status'] = 'NO';
}
else {
$_SESSION['writing_status'] = 'YES';
}
$mysqli->close();
header('Location: '.$url['root'].'bbs/write_done.php');
exit();
?>
I am new to PHP and trying to implement a method by which a user can be added to the database, I am following a tutorial and before I went to work, it was working fine, but now, it is stopping at this statement:
//Check the form token is valid
else if($_POST['formToken'] != $_SESSION['formToken'])
{
$message = 'Invalid form submission';
}
Is there something I'm missing? Full code:
AddUser.php
<?php
//Begin our session
session_start();
//set a form token
$formToken = md5( uniqid('auth', true) );
//set the session form token
$_SESSION['formToken'] = $formToken;
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Add User</h2>
<form action="addUserSubmit.php" method="post">
<fieldset>
<p>
<label for="Username">Username</label>
<input tupe="text" id="Username" name="Username" value="" maxlength="20" />
</p>
<p>
<label for="Password">Password</label>
<input tupe="text" id="Password" name="Password" value="" maxlength="20" />
</p>
<p>
<input type="hidden" name="formToken" vale="<?php echo $formToken; ?>" />
<input type="submit" value="$rarr; Login" />
</p>
</fieldset>
</form>
</body>
</html>
addUserSubmit.php
<?php
//begin our session
session_start();
//Check if username, password and form token have been sent
if(!isset($_POST['Username'], $_POST['Password'], $_POST['formToken']))
{
$message = 'Please enter a valid username and password';
}
//Check the form token is valid
else if($_POST['formToken'] != $_SESSION['formToken'])
{
$message = 'Invalid form submission';
}
//Check the username is the correct length
else if (strlen($_POST['Username']) > 20 || strlen($_POST['Usernamw']) < 4)
{
$message = 'Incorrect Username lenght, please try again';
}
//Check the username only has alpha numeric characters
else if (ctype_alnum($_POST['Username']) != true)
{
$message = "Username must be alpha numeric";
}
else if (ctype_alnum($_POST['Password']) != true)
{
$message = "Password must be alpha numeric";
}
else
{
//Enter the data into the database
$username = filter_var($_POST['Username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['Password'], FILTER_SANITIZE_STRING);
//Encrypt the password
$password = shal($password);
//Connect to the database
$SQLusername = "name";
$SQLpassword = "password";
$SQLhostname = "localhost";
$databaseName = "jfitness";
try
{
//connection to the database
$dbhandle = mysql_connect($SQLusername, $SQLpassword, $SQLhostname)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db($databaseName, $dbhandle)
or die("Could not select database");
$sql = "INSERT INTO
customers (Username, Password)
VALUES
('$_POST[$username]','$_POST[$password]')";
if(!mysql_query($sql, $dbhandle))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
//close the connection
mysql_close($dbhandle);
}
catch (Exception $ex)
{
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<p><?php echo $message; ?>
</body>
</html>
There is a typo I think.. Try changing,
<input type="hidden" name="formToken" vale="<?php echo $formToken; ?>" />
to:
<input type="hidden" name="formToken" value="<?php echo $formToken; ?>" />
I've got a big issue with my website. I've made a profile page which will allow users to amend their details, and then submit. Upon submitting the details should be updated in the database, however I just get a blank page and nothing happens. I've been up for 30+ hours trying to figure things out but no luck. It's likely to be screwed up, as now is my brain.
Any help would be GREATLY appreciated.
Profile amend page:
<?php
session_start();
if (!isset($_SESSION['Username'])) {
echo 'Welcome, '.$_SESSION['Username'];
} else {
echo 'Sorry, You are not logged in.';
}
?>
<!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=utf-8" />
<title>Index</title>
<link href="External style sheet layout.css" rel="stylesheet" type="text/css" />
<h1><?php echo date("D M d, Y G:i a"); ?>
<?php $welcome = 'Hi';
if (date("H") < 12) {
$welcome = 'Good Morning';
} else if (date('H') > 11 && date("H") < 18) {
$welcome = 'Good Afternoon';
} else if(date('H') > 17) {
$welcome = 'Good Evening';
}
echo $welcome;
?></h1>
<div class="Login">
<h3><ul>
<?php if(isset($_SESSION['authenticatedUser']) && $_SESSION['authenticatedUser'] != null ) {?>
<li>Welcome <?php echo $_SESSION["authenticatedUser"] ?></li>
<li><span>Log Out</span></li>
<?php } else {?> <li><span>Log In</span></li> <?php } ?>
<li>Register</li>
<li>Basket</li>
</ul></h3>
</div>
</head>
<body>
<div id="container">
<div id="header">
<img src="Images/Schurter3.jpg" width="800" height="300" alt="Schurter" />
</div>
<div id="navigation">
<ul id="navbar">
<li>Home</li>
<li>Components
<ul>
<li>Circuit Protection
<li>Connectors</li>
<li>Switches</li>
<li>EMC Products</li>
<li>Other Products</li>
</ul>
</li>
<li>Electronic Manufacturing Services
<ul>
<li>Application Examples</li>
<li>Processes</li>
</ul>
</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
<?php
include 'db.inc';
//Check to see if a customer ID has been passed in the URL
$memberID = $_GET["memberID"];
// Has a custID been provided? If so, retrieve the customer
// details for editing.
if (!empty($memberID))
{
$connection = mysql_connect($hostname, $username, $password) or die ("Unable to connect!");
// select database
mysql_select_db($databasename) or die ("Unable to select database!");
$query = "SELECT * FROM members WHERE id = " . $memberID;
//Get the recordset
$recordSet = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
$row = mysql_fetch_assoc($recordSet);
//Check for errors
//if (!$recordSet)
// print $connection->ErrorMsg();
// else
// {
// Load all the form variables with customer data
$Firstname = $row['Firstname'];
$Surname = $row['Surname'];
$Emailaddress = $row['Emailaddress'];
$Username = $row['Username'];
$Password = $row['Password'];
// }//End else
}
?>
<form name="RegisterForm" action="ProfileUpdate.php" method="post" >
<input type="hidden" name="memberID" value="<?php echo $memberID;?>">
<label>First name*</label>
<input name="Firstname" placeholder="Enter first name here" value="<?php echo $Firstname;?>" required/>
<label>Surname*</label>
<input name="Surname" placeholder="Enter surname here" value="<?php echo $Surname;?>" required/>
<label>Email*</label>
<input name="Emailaddress" type="email" placeholder="Enter email here" value="<?php echo $Emailaddress;?>" required/>
<label>Username*</label>
<input name="Username" type="text" placeholder="Enter a desired username" value="<?php echo $Username;?>" required/>
<label>Password*</label>
<input name="Password" type="password" placeholder="Enter a desired password" value="<?php echo $Password;?>" required/>
<input id="submit" name="submit" type="submit" value="Update Details">
</form>
</body>
</html>
And this is the update action page:
<?php
require('db.inc');
$memberID = $_GET["id"];
echo $memberID;
// trim the POSTed values - gets rid of unecessary whitespace
$Firstname = $_POST['Firstname'];
$Surname = $_POST['Surname'];
$Emailaddress = $_POST['Emailaddress'];
$Username = $_POST['Username'];
$Password = $_POST['Password'];
//Here we use validation at the server
// Vaildate the firstname
?>
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head><title>Customer Details Error</title></head>
<body bgcolor="white">
<h1>Customer Details Error</h1>
<?=$errorString?>
<br>Return to the customer form
</body>
</html>
<?php
// If we made it here, then the data is valid
$connection = mysql_connect($hostname, $username, $password) or die ("Unable to connect!");
// select database
mysql_select_db($databasename) or die ("Unable to select database!");
// this is an update
if (!empty($memberID))
{
$query = "UPDATE members SET ".
"Firstname = '$Firstname', Surname = '$Surname', " .
"Emailaddress = '$Emailaddress', Username = '$Username', Password = '$Password', " .
" WHERE id = $memberID";
$recordSet = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
echo "Your updates are complete!";
}
?>
<?php
session_start();
if (!isset($_SESSION['Username'])) {
echo 'Welcome, '.$_SESSION['Username'];
} else {
echo 'Sorry, You are not logged in.';
}
?>
Fix this one to:
<?php
session_start();
if (isset($_SESSION['Username'])) {
echo 'Welcome, '.$_SESSION['Username'];
} else {
echo 'Sorry, You are not logged in.';
}
?>
The first one is wrong, it checks for a username if there is no username then it displays the username else it doesnt.
On-topic:
<form name="RegisterForm" action="ProfileUpdate.php" method="post" >
Change the above line to:
<form name="RegisterForm" action="ProfileUpdate.php?id=<?php echo $memberID ?>" method="post" >
As your profileUpdate.php is requesting a member ID, this is necessary and after this, the code should work!
I'm having a lot of trouble with the $_SESSION variable. I'm trying to create a way for users to log in and out. I can log a user in but i don't seem to be able to maintain the session when i switch page. When the user correctly logs in they are taken to profile.php. But if i return to index.php the following error is printed:
Notice: Undefined index: login in /Applications/MAMP/htdocs/www/Shared sites/userlogreg/index.php on line 3
I'm quite new to this but from looking on SO and elsewhere i can't seem to figure it out. Any help would be appreciated.
index.php
<?php
session_start();
if ($_SESSION['login'] == 1) {
echo "<h1>Logged in!</h1>";
} else {
echo "<h1>Not logged in</h1><br/>";
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Index page</title>
</head>
<body>
<h2>Login</h2>
<form action="login.php" method="POST">
<div>
<label for="emailSignIn">Email:</label>
<input type="email" name="email" placeholder="Email" required="required" />
</div>
<div>
<label for="passwordSignIn">Password:</label>
<input type="password" name="password" placeholder="Password" required="required" />
</div>
<input type="submit" name="submit" value="Sign in" />
</form>
<h2>Register</h2>
<form action="register.php" method="POST">
<div>
<label for="firstnameRegister">First name:</label>
<input type="text" name="firstname" placeholder="First name" required="required" />
</div>
<div>
<label for="lastnameRegister">Last name:</label>
<input type="text" name="lastname" placeholder="Last name" required="required" />
</div>
<div>
<label for="emailRegister">Email:</label>
<input type="email" name="email" placeholder="Email" required="required" />
</div>
<div>
<label for="passwordRegister">Password:</label>
<input type="password" name="password" placeholder="Password" required="required">
</div>
<input type="submit" name="submit" value="Create account" />
</form>
</body>
</html>
login.php
<?php
$email = sanitize_input($_POST['email']); //echo "Sanitized email: ".$email; echo "<br/>";
$password = $_POST['password']; //echo "Inputted password: ".$password; echo "<br/>";
if ((!isset($email)) || (!isset($password))) {
// VISITOR NEEDS TO ENTER AN EMAIL AND PASSWORD
//echo "Data not provided";
} else {
// CONNECT TO MYSQL
$mysql = mysqli_connect("localhost", "root", "root");
if(!$mysql) {
//echo "Cannot connect to PHPMyAdmin.";
exit;
} else {
}
}
// SELECT THE APPROPRIATE DATABASE
$selected = mysqli_select_db($mysql, "languageapp");
if(!$selected) {
//echo "Cannot select database.";
exit;
} else {
}
// GET THE USER'S UNIQUE SALT FROM THE DATABASE
$unique_salt = mysqli_query($mysql, "select uniqueSalt from user where email = '".$email."'");
$row = mysqli_fetch_array($unique_salt);
//echo "Salt: ".$row['uniqueSalt']; echo "<br/>";
// HASH THE PASSWORD
$iterations = 10;
$hashed_password = crypt($password,$row['uniqueSalt']);
for ($i = 0; $i < $iterations; ++$i)
{
$hashed_password = crypt($hashed_password . $password,$row['uniqueSalt']);
}
//echo "Password entered by user: ".$hashed_password; echo "<br/>";
$user_db_password = mysqli_query($mysql, "select password from user where email = '".$email."'");
$row = mysqli_fetch_array($user_db_password);
//echo "User's password: ".$row['password']; echo "<br/>";
// query the database to see if there is a record which matches
$query = "select count(*) from user where email = '".$email."' and password = '".$hashed_password."'";
$result = mysqli_query($mysql, $query);
if(!$result) {
//echo "Cannot run query.";
exit;
}
$row = mysqli_fetch_row($result);
$count = $row[0];
if ($count > 0) {
session_start();
$_SESSION['login'] = 1;
$_SESSION['email'] = $email;
$_SESSION['errors'] = "";
header("location:profile.php");
//echo "<h1>Login successful!</h1>";
//echo "<p>Welcome.</p>";
//echo "<p>This page is only visible when the correct details are provided.</p>";
} else {
session_start();
$_SESSION['login'] = '';
header("location:index.php");
//echo "<h1>Login unsuccessful!</h1>";
//echo "<p>The email and password combination entered was not recognized</p>";
}
// CLEAN THE INPUT
function sanitize_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Change this line:
if ($_SESSION['login'] == 1) {
..to this:
if (isset($_SESSION['login']) && $_SESSION['login'] == 1) {
That way, you check if 'login' is set before you access it.