i have a problem with my website , problem is with this one:
When i try to login and i enter a correct login info,i am keep getting stucked on process_login page and header dont want to redirect me back to index page...This is only happening on my webpage , on localhost everything is going perfectly fine..
Code:
login modal
<div class="modal fade" id="login" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<center><div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<div class="alert alert-info">Login page</div>
</div></center>
<div class="modal-body">
<form role="form" action="process_login.php" method="post">
<div class="form-group">
<label for="exampleInputUsername">Username</label>
<input type="text" name="username" class="form-control" id="username_login" placeholder="Enter username"><span id="span_username_login"></span>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" name="password" class="form-control" id="password_login" placeholder="Password"><span id="span_password_login"></span><br/>
</div>
<a href="#recover" data-toggle="modal" ><p>I've forgotten my password</a></p>
<div class="modal-footer">
<center><input type="submit" name="submit" class="btn btn-danger" value="Sign in"/></center>
</div>
</form>
</div>
</div>
</div>
</div>
process_login.php page
<?php
require_once 'includes/initialize.php';
require_once 'classes/database.php';
require_once 'classes/bcrypt.php';
require_once 'classes/user.php';
if(isset($_POST['submit']))
{
$username = filter_input(INPUT_POST, 'username' , FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password' , FILTER_SANITIZE_STRING);
//if input fields ain't filled , redirecting back to index page
if(empty($username) || empty($password))
{
$_SESSION['emptyfields'] = '';
header("Location: index.php");
}
//if that particular username doesnt exist in database , redirecting back to index page
if($userclass->userExists($username) == false)
{
$_SESSION['usernamedoesntexist'] = '';
header("Location: index.php");
}
//if that particular email isnt confirmed yet , redirecting back to index page
if($userclass->emailConfirmed($username) == false)
{
$_SESSION['emailnotconfirmed'] = '';
header("Location: index.php");
}
if($userclass->banned($username) == false)
{
//if that particular username is banned , redirecting back to index page
$_SESSION['banned'] = '';
header("Location: index.php");
}
$login = $userclass->login($username, $password);
if($login == false)
{
$_SESSION['errorwithlogin'] = ''; //incorect username - password combo
header("Location: index.php");
}
else
{
$_SESSION['user_auth'] = TRUE; //corect username - password combo
$_SESSION['user_id'] = $login;
$_SESSION['loginsuccessfull'] = '';
header("Location: index.php");
}
}
else
{
$_SESSION['errorwithprocessing'] = '';
header("Location: index.php");
}
?>
<?php
unset($_SESSION['errorwithprocessing']);
unset($_SESSION['loginsuccessfull']);
unset($_SESSION['errorwithlogin']);
unset($_SESSION['banned']);
unset($_SESSION['emailnotconfirmed']);
unset($_SESSION['usernamedoesntexist']);
unset($_SESSION['emptyfields']);
?>
class user.php page(rows that have connection with logging in)
public function login($username, $password)
{
global $db;
global $bcrypt;
$stm = $db->connection->prepare("SELECT `user_id`,`password` FROM `users` WHERE `username` = ?");
$stm->bindValue(1, $username);
try
{
$stm->execute();
$data = $stm->fetch();
$stored_password = $data['password'];
$id = (int) $data['user_id'];
if($bcrypt->verify($password, $stored_password) === true)
{
return $id;
}
else
{
return false;
}
}
catch(PDOException $e)
{
die($e->getMessage());
}
}
Any help is welcome , thanks in advance..
From what I can see I am assuming you are starting a session before you get to the redirecting code. Maybe in one of your included files? Whatever the case you will want to call all header() functions before calling session_start(). From my experience, not doing so caused unpredictable results depending on the version of PHP I was running and the server.
However, I do understand that this is not always an option, and with this in mind, I use the following code as a workaround for header("Location:index.php"); This will do the redirect using javascript.
echo '<script type="text/javascript">window.location="index.php";</script>';
Related
I'm trying to make a simple login with a mySQL database. As of right now, I am able to connect to the database just fine, but for whatever reason I cannot for the life of me manage to figure out why it won't accept the data for the username and password (not worried about hashing right now, this is just practice). Each time I type it in it only gives me the error message, and I am trying to use the user 'test' with a password of '123', so I know I'm not spelling it incorrectly. Aside from my error message, it doesn't say anything else is wrong at all. This is what my login looks like currently:
<?php
//Start PHP session
session_start();
require_once("db_config.php");
function sanitize($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//Check if the form has been submitted
if(strtoupper($_SERVER['REQUEST_METHOD']) === 'POST') {
if (isset($_POST['pass']) && isset($_POST['user'])) {
//Predefine variables
$validationed = false;
$err_msg = "";
//Username and password has been submitted by the user
//Receive and sanitize the submitted information
$user = sanitize($_POST['user']);
$passwd = sanitize($_POST['pass']);
$user = mysqli_real_escape_string($conn, $user);
$sql = "SELECT * FROM user_logins WHERE username = '$user';";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$row_count=mysqli_num_rows($result);
//If the record is found, check password.
if ($row_count > 0) {
$row = mysqli_fetch_assoc($result);
if (password_verify($passwd, $row['pass'])) {
$validationed = true;
}
}
if ($validationed === false) {
// If the check completes without finding a valid login, set the error message.
$err_msg = "Invalid Login...Please Try Again";
} else {
// redirect to the main page of the website.
header("Location: travel.php");
exit();
}
}
}
else {
session_destroy();
session_unset();
session_start();
}
?>
<body id="LoginForm">
<div class="container">
<div class="login-form">
<div class="main-div">
<div class="panel">
<h1>Login</h1>
<p>Please enter your username and password</p>
</div>
<?php
//If $err_msg is set, display the message
if(isset($err_msg)) {
echo('<div class="alert alert-danger" role="alert">');
echo(' <strong>' . $err_msg . '</strong>');
echo('</div>');
}
?>
<form id="Login" action="login.php" method="post">
<div class="form-group">
<input type="username" class="form-control" name="user" placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control" name="pass" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary" name='submit'>Login</button>
</form>
</div>
</div>
</div>
</body>
I am trying to access 'username' and 'pass' from the table 'user_logins'. There's obviously something I've done incorrectly, but I can't seem to pick it out. It would be a great help if someone could look over this and tell me if they see anything wrong! Thank you!
When using password_verify to compare password and hash, you must make sure that the hash value was created using the accompanying function password_hash. These two functions work hand-in-hand.
So either you compare both values directly or store the password in its hashed form into the DB (using password_hash).
if ($passwd == $row['pass']) {
$validationed = true;
}
when I go to the page that I put the authentication code it will ask me to log in first before login. The issues are after I logged in it doesn't go to the page that wanted to go and after that clicked to the same page again it ask me to log in again. Am I did something wrong here!?
loginform.php
<div class="container">
<div class="row">
<di class="col-md-4 col-md-offset-4">
<fieldset>
<legend>Login </legend>
<form method="post" action="loginProcess.php">
<div class="form-group">
<label>User name:</label>
<input type="text" name="username" class="form-control" required>
</div>
<div class="form-group">
<label>Password:</label><input type="password" name="password" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Login" class="btn btn-default pull-right">
</div>
</form>
</fieldset>
</di>
</div>
loginProcess.php
<?php
session_start();
include ("dbCon.php");
$username = filter_has_var(INPUT_POST, 'username') ? $_POST['username']: null;
$passWD = filter_has_var(INPUT_POST, 'password') ? $_POST['password']: null;
$sql = "SELECT passwordHash FROM te_users WHERE username = ?";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $passWDHash); //Get the password hash from the query results for the given username and store it in the variable indicated
if(!empty($username)){
if(!empty($passWD)){
if (mysqli_stmt_fetch($stmt)) { //Check if a record was returned by the query.
if (password_verify($passWD,$passWDHash)){
$username = $_SESSION['username'];
$login = $_SESSION['login'];
$_SESSION['login'] = true;
header("location:index.php");
}
else
{
echo "<p>Sorry, we don't seem to have that password.</p>";
}
}
else {
echo "<p>Sorry, we don't seem to have that username.</p>";
}
}
else {
echo "<p>Please enter the password.</p>";
}
}
else {
echo "<p>Please enter the username.</p>";
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>
otherpage.php
this is the code that use for authentication
if( empty($_SESSION['logged_in']) )
{
header('Location:login.php');
exit;
}
else
{
}
You are doing things the wrong way round in the section that registers the successful login, and also setting a different $SESSION variable name than the one you check in your are they logged in code.
if (password_verify($passWD,$passWDHash)){
//$username = $_SESSION['username'];
//$login = $_SESSION['login'];
//$_SESSION['login'] = true;
$_SESSION['username'] = $username;
$_SESSION['logged_in'] = true;
header("location:index.php");
} else {
echo "<p>Sorry, we don't seem to have that password.</p>";
}
Also remember to start the session in any script that want to use the session
<?php
session_start();
if( empty($_SESSION['logged_in']) ) {
header('Location:login.php');
exit;
} else {
}
Heres the issue, I am trying to login with the correct info (triple checked through phpmyadmin) but all it is doing is redirecting back to the login page like the info is not right.
Login Form (at the top of page)
<?php
session_start();
include "includes/class.users.php";
if(isset($_POST['login'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$users->login($email, $password);
}
?>
Login Form
<form method="POST" action="" name="login">
<div id="wrappermiddle">
<h2>Login</h2>
<div id="username_input">
<div id="username_inputleft"></div>
<div id="username_inputmiddle">
<input name="email" type="text" id="myusername" placeholder="Email Address">
<img id="url_user" src="./images/mailicon.png" alt="">
</div><!--ends username_inputmiddle-->
<div id="username_inputright"></div>
</div><!--ends username_input-->
<div id="password_input">
<div id="password_inputleft"></div>
<div id="password_inputmiddle">
<input name="password" type="password" id="mypassword" placeholder="Password">
<img id="url_password" src="./images/passicon.png" alt="">
</div><!--ends password_inputmiddle-->
<div id="password_inputright"></div>
</div><!--ends password_input-->
<div id="submit">
<input type="image" src="./images/submit.png" name="login" value="Login">
</form>
class.users.php
<?php
include "class.database.php";
class Users extends Database {
public function login($email, $password) {
$stmt = $this->mysqli->prepare("SELECT email, password FROM members WHERE email = ? AND password = ? LIMIT 1");
$stmt->bind_param('ss', $email, $password);
$stmt->execute();
$stmt->bind_result($email, $password);
$stmt->store_result();
if($stmt->num_rows == 1) {
while($stmt->fetch()) {
session_start();
$_SESSION['loggedin'] = true;
header("Location: dashboard.php");
}
} else {
return false;
}
$stmt->close();
$stmt->free_result();
}
}
$users = new users();
?>
dashbord.php at the top
<?PHP
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
} else {
header ("Location: index.php");
}
?>
EDIT - I tried loggin in with a bad password and I get the error - There is an error
When I login with the correct info, if just refreshes the login page.
I think the problem is you're setting the header after some html has been rendered.
My approach would be to include in the Login page
if ($_SESSION['loggedin] = true) {
header("Location: dashboard.php");
} else {
login page
}
I'm trying to create a login form form my php site, I have the following code:
<?php
session_start();
require("includes/connect.php");
?>
<div class="container">
<form class="form-signin" role="form" action="login.php" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="text" class="form-control" placeholder="Username" name="username_login" required autofocus>
<input class="form-control" type="password" placeholder="Password" name="user_password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
<label class="forgotten">Forgotten password?</label>
</form>
<?php
//if an admin or user session is already in progress then dont let them log in, redirect to 'index.php'
if (isset($_SESSION['admin']) && ($_SESSION['admin'] == true) || isset($_SESSION['user']) && ($_SESSION['user'] == true)) {
header ("Location: index.php");
//if use not logged in then
}else{
//if username and password are entered, blank before user fills form
$usr = (isset($_POST['username_login'])? $_POST['username_login']:null);
$pwd = (isset($_POST['user_password'])? $_POST['user_password']:null);
$usr = mysqli_escape_string($conn, $usr); //Prevent against SQL Injection by avoiding "\" being executed
$pwd = mysqli_escape_string($conn, $pwd); //Prevent against SQL Injection by avoiding "\" being executed
if ($usr && $pwd){
$epwd = $pwd;
$q = "SELECT * FROM users WHERE UName='$usr' LIMIT 1;";
$resultset = mysqli_query($conn,$q);
$rowcount = mysqli_num_rows($resultset);
if ($rowcount==1){
while ($userRow = mysqli_fetch_assoc($resultset)){
//Get the DB username and password to compare
$dataBaseEmail = $userRow['UName'];
$dataBasePass = $userRow['Password'];
$userGroup = $userRow['UserLevelID'];
}
mysqli_free_result($resultset);
unset($q);
//Compare DB user and pass to those entered
if ($usr == $dataBaseEmail && $epwd == $dataBasePass){
//Now that we know they are activated ect, we can create a session based on their privlidges
if ($userGroup ==1){ //ADMIN load the console
header("Location: index.php");
$_SESSION['admin'] = true;
}else{ //Normal User
header ("Location: logout.php");
$_SESSION['user'] = true;
$_SESSION['user'] = $dataBaseEmail;
}
}else{//user and pass do not match DB
echo '<div class="login-error">Incorrect Password, try again</div>';
}
}else{
echo '<div class="login-error">Error: There is no such user registered on the system. Please check the username and password entered.</div>';
}
}
}
?>
</div> <!-- /container -->
I'm sure I had this working previously, but now when you enter your username and password it just refreshes the form with no error message or anything and I have no idea why?
header statements have to be used before any html code. Source: http://pl1.php.net/manual/en/function.header.php
check your code again , your query keep ruining after admin session check because you didn't added if form posted check
at this line
if (isset($_SESSION['admin']) && ($_SESSION['admin'] == true) || isset($_SESSION['user']) && ($_SESSION['user'] == true)) {
header ("Location: index.php");
//if use not logged in then
}else{
add another if statement after else
if (isset($_SESSION['admin']) && ($_SESSION['admin'] == true) || isset($_SESSION['user']) && ($_SESSION['user'] == true)) {
header ("Location: index.php");
//if use not logged in then
}else
if ( trim($_POST['username_login']) AND trim($_POST['user_password']))
{
You'l have to change location of LOGIN code to before HTML tags, because header() won't work after header send any output to client's browser.
<?php
session_start ();
require ("includes/connect.php");
//Check for FORM POST
if (isset ( $_POST ['username_login'] ) && isset ( $_POST ['user_password'] )) {
// if an admin or user session is already in progress then dont let them log in, redirect to 'index.php'
if (isset ( $_SESSION ['admin'] ) && ($_SESSION ['admin'] == true) || isset ( $_SESSION ['user'] ) && ($_SESSION ['user'] == true)) {
header ( "Location: index.php" );
// if use not logged in then
} else {
// if username and password are entered, blank before user fills form
$usr = (isset ( $_POST ['username_login'] ) ? $_POST ['username_login'] : null);
$pwd = (isset ( $_POST ['user_password'] ) ? $_POST ['user_password'] : null);
$usr = mysqli_escape_string ( $conn, $usr ); // Prevent against SQL Injection by avoiding "\" being executed
$pwd = mysqli_escape_string ( $conn, $pwd ); // Prevent against SQL Injection by avoiding "\" being executed
if ($usr && $pwd) {
$epwd = $pwd;
$q = "SELECT * FROM users WHERE UName='$usr' LIMIT 1;";
$resultset = mysqli_query ( $conn, $q );
$rowcount = mysqli_num_rows ( $resultset );
if ($rowcount == 1) {
while ( $userRow = mysqli_fetch_assoc ( $resultset ) ) {
// Get the DB username and password to compare
$dataBaseEmail = $userRow ['UName'];
$dataBasePass = $userRow ['Password'];
$userGroup = $userRow ['UserLevelID'];
}
mysqli_free_result ( $resultset );
unset ( $q );
// Compare DB user and pass to those entered
if ($usr == $dataBaseEmail && $epwd == $dataBasePass) {
// Now that we know they are activated ect, we can create a session based on their privlidges
if ($userGroup == 1) { // ADMIN load the console
header ( "Location: index.php" );
$_SESSION ['admin'] = true;
} else { // Normal User
header ( "Location: logout.php" );
$_SESSION ['user'] = true;
$_SESSION ['user'] = $dataBaseEmail;
}
} else { // user and pass do not match DB
echo '<div class="login-error">Incorrect Password, try again</div>';
}
} else {
echo '<div class="login-error">Error: There is no such user registered on the system. Please check the username and password entered.</div>';
}
}
}
}
?>
<!-- container -->
<div class="container">
<form class="form-signin" role="form" action="login.php" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="text" class="form-control" placeholder="Username"
name="username_login" required autofocus>
<input class="form-control" type="password" placeholder="Password" name="user_password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
<label class="forgotten">
Forgotten password?</label>
</form>
</div>
<!-- /container -->
".mysql_errno();
}
}
else
{
echo mysql_error()."".mysql_errno();
}
//echo $userName."-".$password;
?>
<form class="form-signin" role="form" action="login.php" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="text" class="form-control" placeholder = "Username"name="username_login" >
<input class="form-control" type="password" placeholder = "password" name="user_password" >
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
<label class="forgotten">Forgotten password?</label>
</form>
This block of code is to login as an admin for the backend of my page I'm building. It parses to the 'else' statement echoing my "Incorrect Information" statement. Basically saying it isn't finding the credentials I created on the server which I have checked and double checked. Also confirmed that my connection script is working. I'm stumped. Any help would be appreciated.
<?php
session_start();
if(isset($_SESSION["manager"])) {
header("location: index.php");
exit();
}
?>
<?php
// Parse the log in form if the user has filled it out and pressed "Log In"
if (isset($_POST["username"]) && isset($_POST["password"])) {
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["username"]); // filter everything but numbers and letters
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["password"]); // filter everything but numbers and letters
// Connect to the MySQL database
include "../php/connect_to_mysql.php";
$sql = mysql_query("SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"); // Query the person
//------MAKE SURE PERSON EXISTS-----
$existCount = mysql_num_rows($sql); // Count the row nums
if ($existCount == 1) {
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: index.php");
exit();
} else {
echo 'That information is incorrect, try again.';
exit();
}
}
?>
This is the form code
<form name="adminform" id="adminform" method="post" action="admin_login.php">
<div class="row collapse">
<div class="large-2 columns">
<label class="inline">Username</label>
</div>
<div class="large-10 columns">
<input type="text" id="username" placeholder="JohnDoe" name="username">
</div>
</div>
<div class="row collapse">
<div class="large-2 columns">
<label class="inline">Password</label>
</div>
<div class="large-10 columns">
<input type="password" id="password" placeholder="Shazam" name="password">
</div>
</div>
<button type="submit" name="button" id="button" class="radius button">Log In</button>
</form>
The problem may be that even if you are checking the $_POST var, when you do the filter you use $_SESSION values. Try with the $_POST one.
// Parse the log in form if the user has filled it out and pressed "Log In"
if (isset($_POST["username"]) && isset($_POST["password"])) {
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]);
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]);
// ...