if($_SERVER['REQUEST_METHOD'] == "POST") is not working - php

This is a my accounts page the user sees once they have logged in, it displays the user details from the database at the top.
I have added the function to change the password but it isn't working.
I'm trying to make it so that when the user clicks the 'submit' button the new password replaces the old password in the database, however the if statement isn't working
When I click the submit button it just refreshes the page because of my else.
ob_start();
$query ="SELECT * FROM Customers WHERE Email='". $_SESSION['Email'] ."'";
$result = mysqli_query($connection,$query);
if ($row = mysqli_fetch_assoc($result)) {
$DFirstName = $row ['FirstName'];
$DLastName = $row ['LastName'];
$DEmail = $row['Email'];
$DPassword = $row ['Password'];
$DGender = $row ['Gender'];
$DAge = $row ['Age'];
echo'Welcome: ' .$DFirstName. ' ' .$DLastName. '<br/>';
echo'Email: ' .$DEmail. '<br/>';
echo'Gender: ' .$DGender. '<br/>';
echo'Age: ' .$DAge;
}else{
echo'error';
}
?>
<h1>Change your password</h1>
<form method="post">
Old Password <input type="password" name"password" value=''/></br>
New Password <input type="password" name"newpassword" value=''/></br>
<input type="submit" name"submit" value="submit"/>
</form>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
if ($_POST['password'] == $_SESSION['password']){
$newpassword = $_POST['newpassword'];
$username = $_SESSION['Email'];
$query = "UPDATE Customers
SET Password = '$newpassword'
WHERE Email = '$username'";
$result = mysqli_query($connection,$query);
//so that the user has to log back in once password has been changed
session_destroy();
header('location:login.php');
} else {echo 'error1';}
}else {echo 'error2';}
ob_flush();
?>
</div>

You have typos in your HTML code:
name"password"
name"newpassword"
name"submit"
You leaved the = sign. Change to this:
name="password"
name="newpassword"
name="submit"

Related

MySQL and PHP Login username and password check [duplicate]

This question already has answers here:
How to check username and password matches the database values
(3 answers)
Closed last month.
So I was following this youtube guide on setting up a log in system with PHP, and I ran into some trouble when I got to the authentication part where the user's username and password are check against the database. Even when a correct username and password that are in the database are submitted, the if statement in login.php echos "Incorrect username or password!"
dbh.php <= this connects to the local databse
<?php
$conn = mysqli_connect("localhost", "admin", "admin", "user_list");
if(!$conn) {
die("Connection failed");
}
?>
sign_up.php <= takes user account info and enters it into the database
<?php
include 'dbh.php';
$first = $_POST['first'];
$last = $_POST['last'];
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
$sql = "INSERT INTO user (first, last, uid, pwd)
VALUES ('$first', '$last', '$uid', '$pwd')";
$result = mysqli_query($conn, $sql);
header("Location: login_page.html");
?>
login.php <= this takes user input and checks to see if a matching pair is in the databse
<?php
include 'dbh.php';
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
$sql = "SELECT * FROM user WHERE uid='$uid' AND pwd='$pwd'";
$result = mysqli_query($conn, $sql);
if (!$row = mysqli_fetch_assoc($result)) {
echo "Your username or password is incorrect!";
} else {
echo "You are logged in!";
}
?>
login_page.html (not full page just login/signup forms)
<div class="content">
<form action="login.php">
<input type="text" name="uid" placeholder="Username"><br>
<input type="password" name="pwd" placeholder="Password"><br>
<button type="submit">LOG IN</button>
<br><br><br>
</form>
<form action="signup.php" method="POST">
<input type="text" name="first" placeholder="Firstname"><br>
<input type="text" name="last" placeholder="Lastname"><br>
<input type="text" name="uid" placeholder="Username"><br>
<input type="password" name="pwd" placeholder="Password"><br>
<button type="submit">SIGN UP</button>
</form>
</div>
Try to use prepared statements in order to avoid SQL injection!
By way of example in your login.php
$mysqli = new mysqli("localhost", "root", "root", "test");
if ($mysqli->connect_errno) {
echo "connect_error" . $mysqli->connect_error;
}
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
$result = $mysqli->prepare('SELECT * FROM user WHERE uid=? AND pwd=?');
$result->bind_param("is", $uid, $pwd);
$result->execute();
$result->bind_result($col1,$col2);
$result->fetch();
$is_valid_profile = ($col1!=null) ? 'You are logged in!' : 'Your username or password is incorrect!';
echo $is_valid_profile;
$result->close();
http://php.net/manual/en/mysqli.prepare.php
You can do like this. This might work
<?php
include 'dbh.php';
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
$sql = "SELECT * FROM user WHERE uid='$uid' AND pwd='$pwd'";
$result = mysqli_query($conn, $sql);
if ($row = mysqli_fetch_assoc($result)) {
echo "You are logged in!";
} else {
echo "Your username or password is incorrect!";
}
?>
You can remove this sign and it will work
OR
this is also a solution
if (mysqli_num_rows($result)) {
echo "You are logged in!";
} else {
echo "Your username or password is incorrect!";
}

Php Mysql login

i have created two tables named login and gotest.in gotest table i have stored user details and unique in that table is ID.in login table i am storing refid, username and password.refid is the primary key which contains same value of ID in gotest table.i am getting from ID from one form when it passed through the URl.but when iam trying to login it gives me this errpor " The Username or password are incorrect! ".
Here is my php code
<?php
include_once 'dbconnect.php';
$renewid = $_GET['ID'];
$query = "SELECT refid, username, password FROM ipay_login WHERE refid = '$renewid'";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$renewid = $row['refid'];
$uname = $row['username'];
$upass = $row['password'];
echo $renewid . '<br />';
echo $uname . '<br />';
echo $upass . '<br />';
}
if(isset($_POST['btn-signup'])) {
$uname = $_POST['username'];
$upass = $_POST['password'];
/*echo $uname,$upass,$renewid;*/
$result1 = mysql_query("SELECT * FROM ipay_login WHERE username = '$uname' AND password = '$upass'");
if(mysql_num_rows($result1) > 0 )
{
echo "sucesss";
}
else
{
echo 'The Username or password are incorrect!';
}
}
?>
<html>
<head></head>
<body>
<form id="convertion" method="post">
<!--<input type="hidden" id="refid" name="refid" value="<?php /*$_GET['refid']; */?>" /><br/>-->
<input type="text" id="username" name="username" /><br/>
<input type="text" id="password" name="password" /><br/>
<button type="submit" id="btn-signup" name="btn-signup">SUBMIT</button>
</form>
</body>
</html>
URL of my login page
http://xxx.yyy.example?ID=1000
Try this ..first of all change your refid column in login to ID.then run following code
<?php
include_once 'dbconnect.php';
$renewid = $_GET['ID'];
$query = "SELECT * FROM login WHERE ID = '$renewid'";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$uname = $row['username'];
$upass = $row['password'];
echo $uname . '<br />';
echo $upass . '<br />';
}
if(isset($_POST['btn-signup'])) {
$uname = $_POST['username'];
$upass= $_POST['password'];
$result1 = mysql_query("SELECT * FROM login WHERE username = '$uname' AND password = '$upass'");
if(mysql_num_rows($result1) > 0 )
{
echo "sucess";
}
else
{
echo 'The username or password are incorrect!';
}
}
?>
<html>
<head></head>
<body>
<form id="convertion" method="post">
<input type="text" id="username" name="username" /><br/>
<input type="text" id="password" name="password" /><br/>
<button type="submit" id="btn-signup" name="btn-signup">SUBMIT</button>
</form>
</body>
</html>

Session Variables from Registration Form not being passed to Login Form

I've been trying to troubleshoot a problem I have but I've had no luck so far.
I have a profile page that echoes the user's first and last name. This function works when users first register. The problem is, however, that when the user logs out (ending session) and logs back in and goes back to his/her profile page, the first and last names do not show, leaving instead blanks.
To better clarify consider the pathways:
1.User registers -> profile displays first and last name
2.User logs in -> profile does not display first and last name
Here are the codes pertaining to this issue (I already have session_start() at the top of each page I have; also, my variables, reg form and login form are under one php enclosure):
Variables:
<?php
error_reporting(E_ALL ^ E_NOTICE);
$reg = $_POST['reg'];
//initializing registration variables to prevent errors
$fn = ""; //first name
$ln = ""; //last name
$em = ""; //email
$em2 = ""; //email 2
$pass = ""; //password
$bday = ""; //birthday
$sud = ""; //sign up date
$em_check =""; //check if email exists
//registration variables + form
$fn = mysqli_real_escape_string($con, $_POST['first_name']);
$ln = mysqli_real_escape_string($con, $_POST['last_name']);
$em = mysqli_real_escape_string($con, $_POST['email']);
$em2 = mysqli_real_escape_string($con, $_POST['email2']);
$pass = mysqli_real_escape_string($con, $_POST['password']);
$bday = date("Y");
$sud = date("Y-m-d H:i:s"); // Year - Month - Day
Registration Form:
if(isset($_POST['reg'])) {
if($em==$em2) {
//check if email already exists
$emSQLI = "SELECT email FROM `users` WHERE email='$em'";
$em_check = mysqli_query($con, $emSQLI); //checks whether both entered emails are identical
$check = mysqli_num_rows($em_check); //count the amount of rows where email = $em
if ($check == 0) {
//check if all fields have been filled
if($fn && $ln && $em && $em2 && $pass && $bday) {
//check the maximum length of relevant fields
if(strlen($fn)>90||strlen($ln)>90) {
echo "Maximum limit for first/last names is 90 characters.";
}
else{
if (strlen($pass)<6||strlen($pass)>99) {
echo "Password must be between 6 and 99 characters long.";
}
else {
$pass = md5($pass);
$regSQLI = "INSERT INTO users (id, email, birth_date, first_name, last_name, password, sign_up_date, activated) VALUES ('','$em','$bday','$fn','$ln','$pass','$sud','0')";
$regQuery = mysqli_query($con, $regSQLI);
//variables that will be passed over from the register fields to forthcoming sessions
$_SESSION["email_login"] = $em;
$_SESSION["first_name"] = $fn;
$_SESSION["last_name"] = $ln;
}
}
header("location: profile.php");
exit();
}
else {
echo '<div id="regerrormsg">Please fill in all required fields. </div>';
}
}
else {
echo '<div id="regerrormsg"> Email is already registered. </div>';
}
}
else {
echo '<div id="regerrormsg">Entered emails do not match. </div>';
}
}
Log In Form:
if(isset($_POST['email_login']) && isset($_POST['pass_login'])) {
$email_login = mysqli_real_escape_string($con, $_POST['email_login']);
$pass_login = mysqli_real_escape_string($con, $_POST['pass_login']);
$pass_login = md5($pass_login);
$logquery = "SELECT id FROM users WHERE email='$email_login' AND password='$pass_login' LIMIT 1";
$sqli = mysqli_query($con, $logquery);
$userCount = mysqli_num_rows($sqli); // Count number of rows returned
// checks the database for respective items
if ($userCount == 1) { //if the search finds a matching record of the login input form
while( $row = mysqli_fetch_assoc($sqli)) { // use fetch_assoc
$id = $row["id"];
}
$_SESSION["email_login"] = $email_login;
$_SESSION["first_name"] = $fn;
$_SESSION["last_name"] = $ln;
header("location: home.php");
exit();
}
else {
echo '<div id="regerrormsg">Login information is invalid. </div>';
}
}
And finally, the profile page that displays the names:
<?php
session_start();
include ( "./inc/connect.inc.php");
if(!isset($_SESSION["email_login"])) {
header("location: index.php");
exit();
}
else {
}
?>
<?php
echo "Delighted to have you here, " .$_SESSION["first_name"]."&nbsp".$_SESSION["last_name"].".";
?>
I am stuck and would like help in troubleshooting this, thank you!
EDIT: Here are the html codes:
Login Form:
<form action="index.php" method="POST">
<input type="email" name="email_login" size="60" placeholder="Email" /><br /><br /><br />
<input type="password" name="pass_login" size="60" placeholder="Password" /><br /><br /><br />
<input type="submit" name="login" id="login" value="LOG IN">
</form>
Register Form:
<form action="index.php" method="POST">
<input type="text" name="first_name" size="15" placeholder="First name" /><br /><br /><br />
<input type="text" name="last_name" size="15" placeholder="Last name" /><br /><br /><br />
<input type="email" name="email" size="15" placeholder="Email" /><br /><br /><br />
<input type="email" name="email2" size="25" placeholder="Re-enter email" /><br /><br /><br />
<input type="password" name="password" size="15" placeholder="New password" /><br /><br /><br />
<p5>Birthyear</p5><br />
<div id="date1" class="datefield">
<input id="birth_year" type="tel" name="birth_year" maxlength="4" placeholder="YYYY" />
</div>
<input type="submit" name="reg" value="Sign Up"><br />
</form>
In your Log form, replace this
$logquery = "SELECT id FROM users WHERE email='$email_login' AND password='$pass_login' LIMIT 1";
$sqli = mysqli_query($con, $logquery);
$userCount = mysqli_num_rows($sqli); // Count number of rows returned
// checks the database for respective items
if ($userCount == 1) { //if the search finds a matching record of the login input form
while( $row = mysqli_fetch_assoc($sqli)) { // use fetch_assoc
$id = $row["id"];
}
$_SESSION["email_login"] = $email_login;
$_SESSION["first_name"] = $fn; // -> $fn not defined
$_SESSION["last_name"] = $ln; // -> $ln not defined
header("location: home.php");
exit();
}
else {
echo '<div id="regerrormsg">Login information is invalid. </div>';
}
By this
$logquery = "SELECT * FROM users WHERE email='$email_login' AND password='$pass_login' LIMIT 1";
$sqli = mysqli_query($con, $logquery);
$userCount = mysqli_num_rows($sqli); // Count number of rows returned
// checks the database for respective items
if ($userCount == 1) { //if the search finds a matching record of the login input form
while( $row = mysqli_fetch_assoc($sqli)) { // use fetch_assoc
$id = $row["id"];
$_SESSION["email_login"] = $row["email"];
$_SESSION["first_name"] = $row["first_name"]; // -> retrieve the data from the result of the query
$_SESSION["last_name"] = $row["last_name"];
}
// EDIT: i moved the $_SESSION part above, my bad !
header("location: home.php");
exit();
}
else {
echo '<div id="regerrormsg">Login information is invalid. </div>';
}
Hope it will help.

my php login doesn't log to home page from the first time

The problem seems to be as follows:
I open the browser.
Point the browser to localhost/myproject/.
login page is loaded on the browser.
I enter the email address and password and click login.
instead of going to the home page the login page reloaded again.
I enter the same email address and password again and click login
this time it goes to the home page correctly??.
and something increase the ambiguity that the problem appears only for the first login. If I logout and login again from the same browser it respond from the first time.
my login code:
<?php
session_start();
if (isset($_SESSION['email']))
header("location:" . $config_basedir);
if (isset($_POST['submit'])) {
$email = trim($_POST['email']);
$email = mysql_real_escape_string($email);
$password= trim($_POST['password']);
$password = mysql_real_escape_string($password);
$query = "select * from users where email= '" . $email .
"' and password= '" . md5($password) . "'";
$result = mysql_query($query, $con);
if ($result != NULL) {
if (mysql_num_rows($result) == 1) {
while ($row = mysql_fetch_array($result)) {
$_SESSION['email'] = $email;
}
header("location: " . $config_basedir);
}
echo "<p style='color:red ;font-size:15px'>****invalid login***</p>";
} else
echo "<p style='color:red ;font-size:15px'>****invalid login****</p>";
}
?>
<html>
<form method="post" action="<?php echo $_SERVER['SCRIPTNAME']; ?>">
<p><input type="text" name="email" value="" placeholder="Email address"></p>
<p><input type="password" name="password" value="" placeholder="Password"></p>
<p class="submit"><input type="submit" name="submit" value="Login"></p>
</form>
</html>
and at the Home page I use:
<?php
session_start();
if (!isset($_SESSION['email']))
header("location:" . $config_basedir . "login.php");
?>
Try this:
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password');
and change
if (mysql_num_rows($result) == 1) {
while ($row = mysql_fetch_array($result)) {
$_SESSION['email'] = $email;
}
header("location: " . $config_basedir);
}
to:
if (mysql_num_rows($result) == 1) {
$_SESSION['email'] = $email;
header("location: " . $config_basedir);
}

cant make login page work

I have this php page that posts to itself and then it checks weather if to login someone or not. The problem I am having is that if it logins... then it still shows the username and password textboxes.. but if i refresh they go away and now the welcome thing comes up thanks to the session.
What i want is to once the submit is clicked and it logs the person in to immediately not show the textboxes (username, password) and show the welcome message. Right now i have to refresh.
Please note i am new to PHP and any wise advise will be much appreciated.
<?php
echo "<form method=\"post\" action=\"index.php?form_type=$page_vals\">";
echo "<body>";
//Start session
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
extract($_POST);
$username = "";
$password = "";
$userrole = "";
$userid ="";
$login_query = "SELECT user_id, user_role, user_username FROM users WHERE user_username = '$_POST[logInUsername]' AND user_password = '$_POST[logInPassword]'";
if(!($database = mysql_connect("localhost","root","")))
die("<p>Could not connect to database</p></div></div>
</body>
</html>");
if(!mysql_select_db("mydatabase", $database))
die("<p>Could not open my databases database</p></div>
</div>
</body>
</html>");
if(!($result = mysql_query($login_query, $database)))
{
print("Could not execute query!<br/>");
die(mysql_error()."</div>
</div>
</body>
</html>");
}
if (mysql_num_rows($result) == 0) {
print("Please verify your login information<br/>");
}
while ($row = mysql_fetch_assoc($result)) {
$username = $row["user_username"];
$userrole = $row["user_role"];
$userid = $row["user_id"];
}
echo "Hello - '$username'";
mysql_close($database);
session_regenerate_id();
$_SESSION['SESS_MEMBER_ID'] = $userid;
$_SESSION['SESS_NAME'] = $username;
//Write session to disc
session_write_close();
echo '<div id="login" class="login">
<label for="login">User Name</label>
<input type="text" name="logInUsername" />
<label for="Password">Password</label>
<input type="password" name="logInPassword" />
<input type="submit" value="Submit" class="button" />
</div>';
}
else
{
$sessionName = $_SESSION['SESS_NAME'];
echo '<div id="login" class="login">
<label for="welcome">Welcome '. $sessionName.'!</label>
</div>';
}
?>
Problem here is just your code is not in sequence. I have corrected Try it now.
<?php
session_start();
echo "<body>";
//Start session
//print_r($_SESSION);exit;
//Check whether the session variable SESS_MEMBER_ID is present or not
extract($_POST);
$username = "";
$password = "";
$userrole = "";
$userid ="";
if(isset($_POST))
{
$login_query = "SELECT reg_id, role_id, f_name FROM registration WHERE f_name = '$_POST[logInUsername]' AND password = '$_POST[logInPassword]'";
if(!($database = mysql_connect("sunlinux","pukhraj","pukhraj123")))
die("<p>Could not connect to database</p></div></div>
</body>
</html>");
if(!mysql_select_db("testbaj", $database))
die("<p>Could not open my databases database</p></div>
</div>
</body>
</html>");
if(!($result = mysql_query($login_query, $database)))
{
print("Could not execute query!<br/>");
die(mysql_error()."</div>
</div>
</body>
</html>");
}
if (mysql_num_rows($result) == 0) {
print("Please verify your login information<br/>");
}
while ($row = mysql_fetch_assoc($result)) {
$username = $row["f_name"];
$userrole = $row["role"];
$userid = $row["reg_id"];
}
$_SESSION['SESS_MEMBER_ID'] = $userid;
$_SESSION['SESS_NAME'] = $username;
}
if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
echo "Hello - '$username'";
mysql_close($database);
session_regenerate_id();
//Write session to disc
session_write_close();
echo "<form method=\"post\" ><div id=\"login\" class=\"login\">
<label for=\"login\">User Name</label>
<input type=\"text\" name=\"logInUsername\" />
<label for=\"Password\">Password</label>
<input type=\"password\" name=\"logInPassword\" />
<input type=\"submit\" value=\"Submit\" class=\"button\" />
</div>";
}
else
{
$sessionName = $_SESSION['SESS_NAME'];
echo "<div id=\"login\" class=\"login\">
<label for=\"welcome\">Welcome '$sessionName' !</label>
</div>";
}
?>
Small changes :
Just plase form tag at appropriate place.
Never mix code after post and before post.
here all database stuff should be execute after submit so I enclosed them in condition if(isset($_POST))
due to nonlinearity of code it was creating session after one more refresh after post data. Now corrected.
for message :
do below changes :
give name to submit button <input type=\"submit\" name=\"submit\" value=\"Submit\" class=\"button\" />
replace first if condition with if(isset($_POST['submit']))
So, not dealing with any of the security or style issues that are here...
Right now you are seeing if the session is set. If it is not, then you process the login. After processing the login, you display the form fields.
You should actually check for 3 states...
Is someone already logged in?
Do you need to process a login?
If neither of those, show normal form...
You can do this by using your existing isset for the session field.
Then if it is not set, check if the post fields are set... if they are set, process a login.
Otherwise, show the basic login form.
EDIT:
Full code sample (sorry for the terrible formatting, mostly cut and paste...:
<?php
echo "<form method=\"post\" action=\"index.php?form_type=$page_vals\">";
echo "<body>";
//Start session
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) != '')) {
$sessionName = $_SESSION['SESS_NAME'];
echo '<div id="login" class="login">
<label for="welcome">Welcome '. $sessionName.'!</label>
</div>';
}
else if ($_POST[logInPassword] != null && $_POST[logInUsername] != null)
{
extract($_POST);
$username = "";
$password = "";
$userrole = "";
$userid ="";
$login_query = "SELECT user_id, user_role, user_username FROM users WHERE user_username = '$_POST[logInUsername]' AND user_password = '$_POST[logInPassword]'";
if(!($database = mysql_connect("localhost","root","")))
die("<p>Could not connect to database</p></div></div>
</body>
</html>");
if(!mysql_select_db("mydatabase", $database))
die("<p>Could not open my databases database</p></div>
</div>
</body>
</html>");
if(!($result = mysql_query($login_query, $database)))
{
print("Could not execute query!<br/>");
die(mysql_error()."</div>
</div>
</body>
</html>");
}
if (mysql_num_rows($result) == 0) {
print("Please verify your login information<br/>");
}
while ($row = mysql_fetch_assoc($result)) {
$username = $row["user_username"];
$userrole = $row["user_role"];
$userid = $row["user_id"];
}
echo "Hello - '$username'";
mysql_close($database);
session_regenerate_id();
$_SESSION['SESS_MEMBER_ID'] = $userid;
$_SESSION['SESS_NAME'] = $username;
//Write session to disc
session_write_close();
$sessionName = $_SESSION['SESS_NAME'];
echo '<div id="login" class="login">
<label for="welcome">Welcome '. $sessionName.'!</label>
</div>';
}
else
{
echo '<div id="login" class="login">
<label for="login">User Name</label>
<input type="text" name="logInUsername" />
<label for="Password">Password</label>
<input type="password" name="logInPassword" />
<input type="submit" value="Submit" class="button" />
</div>';
}
?>
Good luck!
Your logic just needs to be rethought. How about something like this? (pseduocode)
if( user is NOT logged in) // Check via session
{
$errors = array();
if( user submitted the form and is trying to log in) // Can be checked with a POST'd variable
{
// Set the session correctly here, query DB, etc.
// If there are any errors, add them to the $error array
}
if( !empty( $errors) || form was not submitted)
{
// Print the form and any errors (like invalid username / password combo)
}
exit; // Stop here
}
// Print welcome message here (since we know if we get here, the user is logged in)

Categories