When a user logs into my website login.php checks if they have the correct username password or if they are an administrator:
session_start ();
$username = '';
$password = '';
$dbusername = '';
$dbpassword = '';
if (isset($_POST['Email']) && isset($_POST['Password']))
{
$username = $_POST['Email'];
$password = md5($_POST['Password']);
$query = mysql_query("SELECT * FROM member WHERE Email ='$username' AND Password='$password'");
$numrow = mysql_num_rows ($query);
// user login
if ($numrow!=0)
{
while ($row = mysql_fetch_assoc($query))
{
$dbusername = $row['Email'];
$dbpassword = $row['Password'];
}
//Check to see if they match
if ($username==$dbusername&&$password==$dbpassword)
{
header("Location: member.php");
$_SESSION ['Email']=$username;
}
}
else
{
// admin login
$query2 = mysql_query("SELECT * FROM admin WHERE Email ='$username' AND Password ='$password'");
$numrow2 = mysql_num_rows ($query2);
if ($numrow2!=0)
{
while ($row = mysql_fetch_assoc($query2))
{
$dbusername = $row['Email'];
$dbpassword = $row['Password'];
}
//Check to see if they match
if ($username==$dbusername&&$password==$dbpassword)
{
header("Location: admin.php");
$_SESSION ['Email']=$username;
}
else{
echo "Incorrect password";
}
}
else{
if ($username!=$dbusername&&$password!=$dbpassword)
{die("That user does not exist!");
}
}
}
}
They are redirected to member.php (relevant code below)
session_start ();
If (logged_in() === true)//Email
echo "Welcome, ".$_SESSION['Email']. "!<br><ahref='logout.php'>Logout</a>";
else
die ("You must be logged in");
This all works fine, the user is logged in and their username displays on the top of the page, but if the user goes back to the homepage or any other page on the website they are no longer logged in. Totally confused on how to do this, any help would be great.
You need to set the Session-variables before you redirect the user
Related
I'm doing a login system for my webpage, when i key in the correct login id and password the page refresh back to the login page. I did all the things correct but the session keep messing things up and I don't know where is the error.
index.php
session_start();
if(!isset($_SESSION['loggedin'])){
header("location:login.php");
}
server.php
if(isset($_POST['login'])){
$username = mysqli_real_escape_string($db,$_POST['Username']);
$password = mysqli_real_escape_string($db,$_POST['password']);
if (empty($username)){
array_push($errors, "Username is required");
}
if (empty($password)){
array_push($errors, "Password is required");
}
if(count($errors) == 0){
$password = md5($password);
$query = "SELECT * FROM register where username='$username' AND password = '$password'";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) == 1){//user found
$logged_in_user = mysqli_fetch_assoc($result);
if ($logged_in_user['type'] == 'admin') {
$_SESSION['loggedin'] = true;
$_SESSION['Username'] = $username;
$_SESSION['id'] = $id;
header('location: admin.php');
}
else{
$_SESSION['loggedin'] = true;
$_SESSION['Username'] = $username;
header('location: index.php');
}
}
}
}
Both pages should have session_start() at the top of code
for example
index.php
<?php
session_start();
server.php
<?php
session_start();
and so on
Another thing offtopic. Prefer using PDO instead of mysqli_ for database access
http://nl1.php.net/manual/pt_BR/book.pdo.php
I know this one has been asked before but have not been able to find a solution on previous questions.
Secure hash and salt for PHP passwords
Password verifying against database using bcrypt
php password_verify not working with database
I'm attempting to hash the password when registering and then verify it when trying to login. The query is retrieving the password associated with the username however isn't being verified correctly.
The problem is the way I am trying to use password_verify but no matter what I'v tried the past few hours I haven't been able to get it working. If anyone could take a look and try spot what I'm doing wrong it would be a great help.
The DB column length is set to 255 and Varchar to allow the full hash entry.
$SQL_Query = "SELECT * FROM user_information WHERE userName = '".$username."'";
$result = mysqli_query($conn, $SQL_Query);
$num_rows = mysqli_num_rows($result);
//below is the algorithm being used on the registration page
//$hash = password_hash($ID, PASSWORD_BCRYPT, array('cost'=>10));
if ($num_rows > 0)
{ //if there is match for the query within the database
while($row = mysqli_fetch_array($result)) //attempts to retrieve the password associated with the username
{
$row['password'];
$stored_hash = $row['password'];
}
if(password_verify($ID, $stored_hash))
{
$_SESSION['login'] = "1";
$_SESSION['username']= $username;
header('Location: stats.php'); //login success
} else {
$errorMessage = "Login Unsuccessful";
$_SESSION['error'] = $errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
} else {
$errorMessage = "Login Unsuccessful";
$_SESSION['error']=$errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
So I know the hash being returned from the database is being set in the $stored_hash variable correctly as if I hard code the hash returned from it and compare it, login is correct. Could it be something altering the input somewhere?
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
Function is_valid_entry($inputData,$validData)
{
$inputData_array = str_split($inputData);
$validData_array = str_split($validData);
$i = 0;
while ($i < sizeof($inputData_array))
{
if (!in_array($inputData_array[$i],$validData_array))
{
return false;
}
$i++;
}
return true;
}
//User defined global variables go here
$username = "";
$ID = "";
$errorMessage = "";
$valid_chars = "abcdefghijklmnopqrstuvwxyz
1234567890";
session_start(); //start a session
if (isset($_POST['submit'])) { //submit button has been clicked
$username = $_POST['username'];
$username = trim($username); //trim any white spaces in the input value
$username = lcfirst($username); //attempts to convert upper case to lower
$username = htmlspecialchars($username); //convert special chars to html rendering null
$username = strip_tags($username); //Strip tags from input string
$ID = $_POST['ID']; //read in the value the user has entered for the password and assign to $ID
$ID = htmlspecialchars($ID);
$ID = strip_tags($ID);
$ID = trim($ID);
if (!is_numeric($ID)) { //if $ID is not numeric redirect to login page
$errorMessage = "Invalid username or password.";
$_SESSION['error'] = $errorMessage; //sets the value of the 'errorMessage' session variable
$_SESSION['login'] = ""; //set the value of the 'login' session variable to ''
//redirect to login page & send error message
header('Location: login.php');
} else if (!is_valid_entry($username,$valid_chars)) { //check that user name is a valid char
$errorMessage = "Invalid username or password";
$_SESSION['error'] = errorMessage; //sets the value of the 'errorMessage' session variable
$_SESSION['login'] = ""; //set the value of the 'login' session variable to ''
//redirect to login page & send error message
header('Location: login.php'); //redirect the user to the login page
} else { //if user name & $id are both valid
//now check if they are in the database
$mySQL_Server = "127.0.0.1";
$db_userName = "root";
$db_password = "";
$database = "projectdatabase";
//connect to the database on the MySQL server & store the connection in $conn
$conn = mysqli_connect($mySQL_Server, $db_userName, $db_password, $database);
if (mysqli_connect_errno($conn))
{
print("Error connecting to MySQL database: " . mysqli_connect_error($conn));
} else
{
print("Connected to the MySQL database");
}
$SQL_Query = "SELECT * FROM user_information WHERE userName = '".$username."'";
$result = mysqli_query($conn, $SQL_Query);
$num_rows = mysqli_num_rows($result);
//below is the algorithm being used on the registration page
//$hash = password_hash($ID, PASSWORD_BCRYPT, array('cost'=>10));
if ($num_rows > 0)
{ //if there is match for the query within the database
while($row = mysqli_fetch_assoc($result)) //attempts to retrieve the password associated with the username
{
$row['password'];
$stored_hash = $row['password'];
}
if(password_verify($ID, $stored_hash))
{
$_SESSION['login'] = "1";
$_SESSION['username']= $username;
header('Location: stats.php'); //login success
} else {
$errorMessage = "$ID, $stored_hash"; //test to ensure is reaching this statement
$_SESSION['error'] = $errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
} else {
$errorMessage = "Login Unsuccessful";
$_SESSION['error']=$errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
mysqli_close($conn);
}
}
?>
if(!$_SESSION['username']) {
$ip = $db->real_escape_string(VisitorIP());
$username = $db->real_escape_string($_POST['username']);
$password = $db->real_escape_string($_POST['password']);
$salt = "****";
$password = md5($password . $salt);
$result = $db->query("SELECT * FROM TABLE WHERE username='$username' and password='$password'");
$count = mysqli_num_rows($result);
if ($count == 1){
$bannedq = $db->query("SELECT banned FROM TABLE WHERE username='$username' AND password='$password'");
$banned = $bannedq->fetch_row();
if($banned[0] == "1") {
$failedLogin="1";
$message = 'You are banned and you cannot login';
} else {
$ip = $db->real_escape_string(VisitorIP());
$db->query("UPDATE h_users SET lastlogin=now(), lastip = '$ip' WHERE username='$username'");
header("Location: home");
session_start();
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$failedLogin = "1";
$message = 'Username or Password WRONG!';
}
}
} else {
header("location: home");
}
Hello programmers,
I am trying to setup a login system in my website. Until now it was working fine but when the session is set and the user gets redirected to the homepage now if he goes to the login screen and the session is set i want him to redirect to the homepage and not see the login screen again.
But my after i added this part :
if(!$_SESSION['username']) {
it does not work
You have to take your session start and put it there before you use it, so write this before your if statement:
session_start();
if(!$_SESSION['username']) {
//...
And delete this one here:
/...
session_start();
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
/...
(Also i would add a die(); or exit(); after each header, it makes sure nothing gets executed after the header)
Okay guys thanks for your help <3 <3
I changed my code to this and everything went fine
session_start();
if(!isset($_SESSION['username'])) {
if(isset($_POST['username']) && isset($_POST['password'])) {
$ip = $db->real_escape_string(VisitorIP());
$username = $db->real_escape_string($_POST['username']);
$password = $db->real_escape_string($_POST['password']);
$salt = "ho073";
$password = md5($password . $salt);
$result = $db->query("SELECT * FROM TABLE WHERE username='$username' and password='$password'");
$count = mysqli_num_rows($result);
if ($count == 1){
$bannedq = $db->query("SELECT banned FROM TABLE WHERE username='$username' AND password='$password'");
$banned = $bannedq->fetch_row();
if($banned[0] == "1") {
$failedLogin="1";
$message = 'You are banned and you cannot login';
} else {
$ip = $db->real_escape_string(VisitorIP());
$db->query("UPDATE TABLE SET lastlogin=now(), lastip = '$ip' WHERE username='$username'");
header("Location: home");
$_SESSION['username'] = $username;
$failedLogin = "1";
$message = 'Username or Password WRONG!';
}
}
}
include'templates/login.html';
} else {
header("location: home");
die();
}
Much love for you <3
my PHP:
I'm trying to get the script to redirect after a user has entered the correct information. I know it has do with:
header("Location: site");
however it's not redirecting after submission. It does login though, because when I refresh, it redirects to the /site
and ideas?
$submit = $_POST['submit'];
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if ($submit) {
if ($username&&$password) {
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows!=0) {
while ($row = mysql_fetch_assoc($query)) {
$dbusername = $row['username'];
$dbpassword = $row['password'];
$rank = $row['rank'];
}
if ($username==$dbusername&&md5($password)==$dbpassword) {
header("Location: site");
$_SESSION['username']=$username;
} else
echo "<div class='alert alert-error'><strong>Error:</strong> Incorrect password!</div>";
}else
echo "<div class='alert alert-error'><strong>Error:</strong> The user you entered doesn't exist!</div>";
}else
echo "<div class='alert alert-error'><strong>Error:</strong> Please enter a username or password!</div>";
}
here's my full code:
Full Short Code
I have the following code:
session_start ();
include 'core/init.php';
$username = '';
$password = '';
$dbusername = '';
$dbpassword = '';
if (isset($_POST['Email']) && isset($_POST['Password']))
{
$username = $_POST['Email'];
$password = md5($_POST['Password']);
$query = mysql_query("SELECT * FROM member WHERE Email ='$username' AND Password='$password'");
$numrow = mysql_num_rows ($query);
// user login
if ($numrow!=0)
{
while ($row = mysql_fetch_assoc($query))
{
$dbusername = $row['Email'];
$dbpassword = $row['Password'];
}
//Check to see if they match
if ($username==$dbusername&&$password==$dbpassword)
{
$_SESSION ['Email']=$username;
header('Location: member.php?username='.$username);
}
}
else
{
// admin login
$query2 = mysql_query("SELECT * FROM admin WHERE Email ='$username' AND Password ='$password'");
$numrow2 = mysql_num_rows ($query2);
if ($numrow2!=0)
{
while ($row = mysql_fetch_assoc($query2))
{
$dbusername = $row['Email'];
$dbpassword = $row['Password'];
}
//Check to see if they match
if ($username==$dbusername&&$password==$dbpassword)
{
$_SESSION ['Email']=$username;
header("Location: admin.php");
}else{
if (empty ($username) === true|| empty($password) === true) {
echo "Please enter a username and password";
} else if ($username!=$dbusername){
echo "That user does not exist! Have you registered?";
} else if ($username=$dbusername&&$password!=$dbpassword) {
echo "Incorrect password";
}
}
}
}
}
But if a user logs in incorrectly, none of the error messages are displaying, just a blank page, I think its my curly brackets but no matter how many times i change them i either make it worse or nothing at all. Can anyone tell me what im doing wrong?
Check out:
if (empty ($username) === true|| empty($password) === true) {
echo "Please enter a username and password";
} else if ($username!=$dbusername){
echo "That user does not exist! Have you registered?";
} else if ($username=$dbusername&&$password!=$dbpassword) {
echo "Incorrect password";
}
}
This section which includes login errors is found in the " admin login " section, therefore no error is seen when a non-admin user login fails.
Your select statement is already ensuring that the provided username and password match what is in the database. There is no need to do a second comparison in PHP. Your code could just be the following:
if (isset($_POST['Email']) && isset($_POST['Password']))
{
$username = $_POST['Email'];
$password = md5($_POST['Password']);
$query = mysql_query("SELECT * FROM member WHERE Email ='$username' AND Password='$password'");
if(mysql_num_rows($query) == 1)
{
$_SESSION['Email'] = $username;
header('location: member.php?username='.$username);
}
else
{
// try admin login
$query2 = mysql_query("SELECT * FROM admin WHERE Email ='$username' AND Password ='$password'");
if(mysql_num_rows($query2) == 1)
{
$_SESSION['Email'] = $username;
header("location: admin.php");
}
else
{
echo "Failed Login Attempt";
}
}
}
Since your query only returns records where the username and password match, there is NO way you will ever get a result back where the username matches but the password didn't, so your conditional check you do near the end of your admin login will NEVER occur.
As a side-note, it would be bad form to inform the user that the username was correct but password wasn't, or visa versa. This is a security issue and could make it easier for a malicious user to more easily gain access. This is besides the point though, so please only take this suggestion as personal advice and not directed at your question.
$query = mysql_query("SELECT * FROM member WHERE Email ='$username' AND Password='$password'");
if(mysql_num_rows($query) == 0){
echo 'You have entered wrong username/password'; }else {
// you can continue with your query below.