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
}
Related
This question already has an answer here:
Check to see if an email is already in the database using prepared statements
(1 answer)
Closed 2 years ago.
I have been trying this for several days now and am having problems with the code. I am trying tp learn php and mysql/MariaDB and am working on a multi user login system that allows for administrators and users.
So far I have the following working:
users can register
users can log-in and log-out if already registered (are directed to an index page based on user level
administrator is directed to "admin" home page based on admin level
administrators can create a new user from admin area (no access for user level)
only difference between registration page and the admin create user page is that the admin create user page allows the assigning the role of either user or admin (no option for this on registration page)
My problem that I am running into is that I want to add a check to prevent the duplication of user names (newly registering users or admin created users can't create a new user if name already taken). I have tried inserting a check to see but it still adds the user even if that username already exists.
I was wondering if someone could look at the code I have and see where I am going wrong.
Here is my administrator create user code:
<?php include('../functions.php') ?>
if (!isAdmin()) {
$_SESSION['msg'] = "You must log in first";
header('location: ../login.php');
}
<!DOCTYPE html>
<html>
<head>
<title>Registration system PHP and MySQL - Create user</title>
<link rel="stylesheet" type="text/css" href="../style.css">
<style>
.header {
background: #003366;
}
button[name=register_btn] {
background: #003366;
}
</style>
</head>
<body>
<div class="header">
<h2>Admin - create user</h2>
</div>
<form method="post" action="create_user.php">
<?php echo display_error(); ?>
<div class="input-group">
<label>Username</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</div>
<div class="input-group">
<label>Email</label>
<input type="email" name="email" value="<?php echo $email; ?>">
</div>
<div class="input-group">
<label>User type</label>
<select name="user_type" id="user_type" >
<option value=""></option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
</div>
<div class="input-group">
<label>Password</label>
<input type="password" name="password_1">
</div>
<div class="input-group">
<label>Confirm password</label>
<input type="password" name="password_2">
</div>
<div class="input-group">
<button type="submit" class="btn" name="register_btn"> + Create user</button>
</div>
</form>
</body>
</html>
**Here is Register page:**
<?php include('functions.php') ?>
<!DOCTYPE html>
<html>
<head>
<title>Registration system PHP and MySQL</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="header">
<h2>Register</h2>
</div>
<form method="post" action="register.php">
<?php echo display_error(); ?>
<div class="input-group">
<label for="username" class="col-md-3 control-label">User Name*</label>
<div class="col-md-9">
<input type="username" class="form-control" name="username" placeholder="User Name" required>
</div>
</div>
<div class="input-group">
<label for="email" class="col-md-3 control-label">Email*</label>
<div class="col-md-9">
<input type="email" class="form-control" name="email" placeholder="Email" required>
</div>
</div>
<div class="input-group">
<label for="password" class="col-md-3 control-label">Password</label>
<div class="col-md-9">
<input type="password" class="form-control" name="password_1" placeholder="Password" required>
</div>
</div>
<div class="input-group">
<label for="password" class="col-md-3 control-label">Confirm password</label>
<div class="col-md-9">
<input type="password" class="form-control" name="password_2" placeholder="Password" required>
</div>
</div>
<div class="input-group">
<button type="submit" class="btn" name="register_btn">Register</button>
</div>
<p>
Already a member? Sign in
</p>
</form>
</body>
</html>
Here are all my functions:
<?php
session_start();
// connect to database
$db = mysqli_connect('removed variables to connect to database this works');
// variable declaration
$username = "";
$email = "";
$errors = array();
// call the register() function if register_btn is clicked
if (isset($_POST['register_btn'])) {
register();
}
function register(){
// call these variables with the global keyword to make them available in function
global $db, $errors, $username, $email;
// receive all input values from the form. Call the e() function
// defined below to escape form values
$username = e($_POST['username']);
$email = e($_POST['email']);
$password_1 = e($_POST['password_1']);
$password_2 = e($_POST['password_2']);
$sql= "SELECT * FROM users WHERE username = '$username'";
$result=mysqli_query($sql);
if(mysqli_num_rows($result)!=0)
{
echo"name already exists";
}
// form validation: ensure that the form is correctly filled
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($email)) {
array_push($errors, "Email is required");
}
if (empty($password_1)) {
array_push($errors, "Password is required");
}
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// register user if there are no errors in the form
if (count($errors) == 0) {
$password = hash('sha256', $password_1);//encrypt the password before saving in the database
// excecute insert query
if (isset($_POST['user_type'])) {
$user_type = e($_POST['user_type']);
$query = "INSERT INTO users (username, email, user_type, password)
VALUES('$username', '$email', '$user_type', '$password')";
mysqli_query($db, $query);
$_SESSION['success'] = "New user successfully created!!";
header('location: home.php');
}else{
$query = "INSERT INTO users (username, email, user_type, password)
VALUES('$username', '$email', 'user', '$password')";
mysqli_query($db, $query);
// get id of the created user
$logged_in_user_id = mysqli_insert_id($db);
$_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
}
// ge
// return user array from their id
function getUserById($id){
global $db;
$query = "SELECT * FROM users WHERE id=" . $id;
$result = mysqli_query($db, $query);
$user = mysqli_fetch_assoc($result);
return $user;
}
// escape string
function e($val){
global $db;
return mysqli_real_escape_string($db, trim($val));
}
function display_error() {
global $errors;
if (count($errors) > 0){
echo '<div class="error">';
foreach ($errors as $error){
echo $error .'<br>';
}
echo '</div>';
}
}
function isLoggedIn()
{
if (isset($_SESSION['user'])) {
return true;
}else{
return false;
}
}
// log user out if logout button clicked
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['user']);
header("location: login.php");
}
// call the login() function if register_btn is clicked
if (isset($_POST['login_btn'])) {
login();
}
// LOGIN USER
function login(){
global $db, $username, $errors;
// grap form values
$username = e($_POST['username']);
$password = e($_POST['password']);
// make sure form is filled properly
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
// attempt login if no errors on form
if (count($errors) == 0) {
$password = hash(sha256, $password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) { // user found
// check if user is admin or user
$logged_in_user = mysqli_fetch_assoc($results);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: admin/home.php');
}else{
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
function isAdmin()
{
if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'admin' ) {
return true;
}else{
return false;
}
}
The function I have been adding the code to is the register function As you can see, I selected all from my users table and assigned it to a variable (the username variable was assigned just above it from the Post Action. I then did a mysqli query on that variable and assigned this to another variable. Then I tried to say if the number of rows did not equal zero, then the username existed.
I am not sure what I am doing wrong. If any can provide some insight, please let me know. I know this code is probably not the best. I am trying this out in my local environment to learn. Any advice would be greatly appreciated.
Thanks in advance.
The propblem is in the mysqli_query function, this function needs at least 2 parameters, the first one is the link to your database, so your code should be something like:
$connection = mysqli_connect("localhost","db_user","db_password","db_name");
/* your code */
$result=mysqli_query($connection, $sql);
i have a login for like the following:
<form action="authenticate.php" method="post">
<label for="username">
<i class="fas fa-user"></i>
</label>
<input type="text" name="username" placeholder="Username" id="username" required>
<label for="password">
<i class="fas fa-lock"></i>
</label>
<input type="password" name="password" placeholder="Password" id="password" required>
<input type="submit" value="Login">
</form>
below is my authenticate.php
<?php
session_start();
include('config.php');
if ( mysqli_connect_errno() ) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
if ( !isset($_POST['username'], $_POST['password']) ) {
die ('Please fill both the username and password field!');
}
if ($stmt = $link->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password);
$stmt->fetch();
if (password_verify($_POST['password'], $password)) {
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
header('Location: index.php');
exit();
} else {
echo 'Incorrect password!';
}
} else {
echo 'Incorrect username!';
}
$stmt->close();
}
i have used the following php code on every header so that the user is redirected if not logged in
<?php
// We need to use sessions, so you should always start sessions using the below code.
session_start();
include('config.php');
// If the user is not logged in redirect to the login page...
if (!isset($_SESSION['loggedin'])) {
header('Location: login.php');
exit();
}
?>
everything is working fine on my localhost, now i uploaded it to server, live the problem is even when i login i am again redirected to login page. here is my website for reference:
enter link description here
can anyone tell me what could be the problem with my code?
i have found out the problem, in future if anyone has the same error hope it helps
domain was pointing to .html website, so the php.ini file was not there, now its added and working fine
Use session_start() before assigning it
if (password_verify($_POST['password'], $password)) {
session_start();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
header('Location: index.php');
exit();
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 {
}
I made a login that worked perfectly, but now im copying the original and editing it to work on another one of my web projects and it jsut dosnt seam to want to work, any help would be appreciated!
Here is the login that worked:
<?php
session_start();
include('../includes/connect-db.php');
if (isset($_SESSION['logged_in'])) {
?>
<html>
<head>
</head>
<body>
<div>Message would go here</div>
</body>
</html>
<?php
} else {
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) or empty($password)) {
$error = 'All fields are required!';
} else {
$query = $pdo->prepare('SELECT * FROM users WHERE user_username = ? AND user_password = ?');
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
} else {
$error = 'Incorrect details!';
}
}
}
?>
<html>
<head>
</head>
<body>
<div>Login form would go here</div>
</body>
</html>
<?php } ?>
And here is the login im trying to get to work (some more info about it under the code):
<?php
//Start Session
session_start();
//Connect To DataBase
include($_SERVER['DOCUMENT_ROOT'].'includes/connect-db.php');
//Login
if (isset($_SESSION['logged_in'])) {
header('Location: http://localhost/logged-in.html');
} else {
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) or empty($password)) {
$error = 'All fields are required!';
} else {
$query = $pdo->prepare('SELECT * FROM admins WHERE admin_username = ? AND admin_password = ?');
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
$_SESSION['logged_in'] = true;
header('Location: http://localhost/techbite/logged-in.html');
exit();
} else {
$error = 'Incorrect details!';
}
}
}
//Page Content
$content = '<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Submit" />
</form>
<?php if (isset($error)) { ?>
<small style="color:#aa0000"><?php echo($error); ?></small>
<?php } ?>';
//Select Theme
include($_SERVER['DOCUMENT_ROOT'].'themes/theme-select.php');
}
?>
Keep in mind that database connection is successful, the login form appears but just dosnt seam to log in or show an error when nothing is entered/wrong credentials, everything else works perfect, including importing the form into the theme with $content.
Here is the connect-db.php:
<?php
//Connect To Database
try {
$pdo = new PDO('mysql:host=localhost;dbname=techbite', 'root', '');
} catch (PDOException $e) {
exit('Database error, could not connect.');
}
?>
What iv done here is included the theme:
include($_SERVER['DOCUMENT_ROOT'].'/themes/theme-select.php');
And inside the theme where i want the content i have:
<?php echo($content); ?>
and in the login php file i have this which will be put into the php theme file:
$content = '<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Submit" />
</form>
<?php if (isset($error)) { ?>
<small style="color:#aa0000"><?php echo($error); ?></small>
<?php } ?>';
I hope someone can help, hopefully its something small i have missed!
Thanks for any help and let me know if anything else is needed.
Kind Regards,
Hayden.
it's not showing an error because
$content = '<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Submit" /> </form>
<?php if (isset($error)) { ?>
<small style="color:#aa0000"><?php echo($error); ?></small>
<?php } ?>';
is all just a string, and the <?php ?> sections inside this string are never parsed by the php interpreter. View the page source of your login page and you should see them there.
If you're set on using this $content variable and the theme-select.php file, try changing it to this:
$content = '<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Submit" /> </form>';
if (isset($error)) {
$content .= '<small style="color:#aa0000">'.$error.'</small>';
}
As for why it's not logging in, it's a silly question, but have you created a table in your database named admins and a record there with a username and password set?
Try replacing
$num = $query->rowCount();
with
$num = count($query->fetchAll(PDO::FETCH_ASSOC));
UPDATE
Just noticed this...
if (isset($_POST['username'], $_POST['password'])) {
should be
if( isset($_POST['username']) && isset($_POST['password']) ) {
I would add an else condition here to display an error message of some description
UPDATE 2
Slight modification to your connect.php
try {
// create a new instance of a PDO connection
$pdo = new PDO('mysql:host=localhost;dbname=techbite', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
// if the connection fails, display an error message
echo 'ERROR: ' . $e->getMessage();
}
I fixed it!
i knew it would be something so small and simple, it was the form action which was set to the wrong file name, it was set to index.php instead of login.php.
Thank you to everyone for your help! :)
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>';