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);
Related
I am trying to display a message if wrong username or password upon login, so I created to functions set_message and display message as following:
function set_message(){
if (!empty($msg)) {
$_SESSION['message'] = $msg;
}else
$msg = "";
}
function message_display(){
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
}
I called set message function here:
function login_user(){
if (isset($_POST['submit'])) {
$username = escape_string( $_POST['username']);
$password = escape_string($_POST['password']);
global $connection;
$query = "SELECT * FROM users WHERE username = '{$username}' AND password = '{$password}' ";
$result = mysqli_query($connection, $query);
confirm($result);
if (mysqli_num_rows($result) == 0) {
set_message("Username or Password Are Wrong!");
message_display();
redirect('login.php');
}else{
set_message("WELCOM ADMIN");
redirect('admin');
}
}
I called display message function in login.php file inside form:
<form class="" action="" method="post" enctype="multipart/form-data">
<?php login_user(); ?>
<h3><?php message_display(); ?></h3>
<div class="form-group"><label for="">
username<input type="text" name="username" class="form-control"></label>
</div>
<div class="form-group"><label for="password">
Password<input type="text" name="password" class="form-control"></label>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-primary" >
</div>
</form>
PROBLEM IS UPON WRONG USER/PASS REDIRECT SUCCESSFULLY EXECUTED BUT WITHOUT MESSAGE DISPLAY
You never call message_display() here:
}else{
set_message("WELCOM ADMIN");
redirect('admin');
)
But you immediately do a redirect (assuming that function is working) so the message would never get displayed unless this is a SPA.
i have a website for users to login and register, the website was working fine when login and register was in 2 different pages, now i have made them both in the same page, the html code is like below:
<h2>Login</h2>
</div>
<form method="post" class="form-detail" action="index.php">
<?php include('errors.php'); ?>
<div style="padding-right: 20px; margin-left: -40px;" class="input-group">
<label>Username</label>
<input type="text" name="username" >
</div>
<div style="padding-right: 20px; margin-left: -40px;" class="input-group">
<label>Password</label>
<input type="password" name="password">
</div>
<div class="input-group">
<button type="submit" class="btn" name="login_user">Login</button>
</div>
</form>
</div>
<form class="form-detail" method="post" action="index.php">
<div class="header">
<h2>Register Now</h2>
</div>
<?php include('errors.php'); ?>
<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>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="reg_user">Register</button>
</div>
the server.php file which does the functionality is like:
<?php
session_start();
// initializing variables
$username = "";
$email = "";
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'teia');
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
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");
}
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO users (username, email, password)
VALUES('$username', '$email', '$password')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
if (isset($_POST['login_user'])) {
$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 users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: profile.php');
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
?>
and finally the error.php is below
<?php if (count($errors) > 0) : ?>
<div class="error">
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
earlier it was working completely fine, now when i added both login and register in same pages, both login and register not working, instead simply loading the page, as i am new to php, can anyone please tell me whats wrong with my code
You can use switch statement for your solutions with different submit button value like below
<button type="submit" class="btn" value="login">Login</button>
<button type="submit" class="btn" value="register">Register</button>
<?php
switch($_POST['submit']) {
case 'login':
//...
break;
case 'register':
//...
break;
}
?>
The problem is that both your form actions point to index.php which isn't where the functionality is.
<form method="post" class="form-detail" action="server.php">
Change both forms to this. That should solve your problem.
Edit:
To display the errors, you'll need access to the $errors variable you defined. One way to do this is to move the code in error.php like so:
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO users (username, email, password)
VALUES('$username', '$email', '$password')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
} else {
include('errors.php');
}
Are you sure; you are adding this <?php include('server.php'); ?> at the top of the index.php page?
I have 2 problems.
Basic story: I have created a SIMPLE registration and login system.
Problem1: If I try to register a new account then it says "user registration failed". At the moment it should say that because mysql can't get right information from forms. But problem is that I don't know why. Everything seems correct...
Problem2: If I try to login with existent account then it seems that browser is only refreshing the page and nothing else...
Registration with php code:
<?php
require ('insert.php');
// If values posted, insert into the database.
if (isset($_POST['username']) && isset($_POST['password'])){
$name = $_POST['name'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
// nimi refers to name, it's correct
$query = "INSERT INTO `user` (nimi, email, username, password)
VALUES('$name', '$email', '$username', '$password')";
//POST retrieves the data.
$result = mysqli_query($connection, $query);
if($result){
$smsg = "User Created Successfully.";
} else {
$fmsg = "User Registration Failed";
}
}
mysqli_close($connection);
?>
<html>
...
<body>
...
<div>
<form method="POST" class="form-horizontal" role="form">
<!-- Status, how registering went -->
<?php if(isset($smsg)){ ?><div class="alert alert-success" role="alert"> <?php echo $smsg; ?> </div><?php } ?>
<?php if(isset($fmsg)){ ?><div class="alert alert-danger" role="alert"> <?php echo $fmsg; ?> </div><?php } ?>
<!-- Registration form starts -->
<h2>Form</h2><br>
<label for="Name"></label>
<input name="name" type="text" id="name" maxlength="40" placeholder="Ees- ja perenimi" class="form-control" autofocus> <!-- lopp -->
<label for="email"></label>
<input name="email" type="email" id="email" maxlength="65" placeholder="Email" class="form-control"> <!-- lopp -->
<label for="Username"></label>
<input name="username" type="text" id="userName" maxlength="12" placeholder="Kasutajatunnus/kasutajanimi" class="form-control" required> <!-- lopp -->
<label for="Password"></label>
<input name="password" type="password" id="password" maxlength="12" placeholder="Parool" class="form-control" required>
<button type="submit" class="btn btn-primary btn-block">Join</button>
</form> <!-- /form -->
</div> <!-- ./container -->
...
</body>
</html>
Login:
<?php
session_start();
require ('insert.php');
//Is username and password typed?
if (isset($_POST['username']) and isset($_POST['password'])){
//Making vars from inputs
$username = $_POST['username'];
$password = $_POST['password'];
//Checking existent of values.
$query = "SELECT * FROM `liikmed`
WHERE username='$username'
and password='$password'";
$result = mysqli_query($connection, $query)
or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
//3.1.2 If values equal, create session.
if ($count == 1){
$_SESSION['username'] = $username;
} else {
//If credentials doesn't match.
$fmsg = "Invalid Login Credentials.";
}
}
//if user logged in, welcome with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hai " . $username . "";
echo "This is the Members Area";
echo "<a href='logout.php'>Logout</a>";
}else{}
?>
<html>
...
<body>
...
<div id="bg"></div>
<form method="POST" class="form-horizontal">
<h2>Login</h2><br>
<label for="User"></label>
<input name="username" type="text" maxlength="15" placeholder="Username" class="form-control" required autofocus>
<label for="Password"></label>
<input name="password" type="password" maxlength="50" placeholder="Password" class="form-control" required autofocus>
<button type="submit" class="btn btn-primary btn-block">Enter</button>
</form>
</div>
...
</body>
</html>
And finally php database connection file (called insert.php):
<?php
$connection=mysqli_connect("localhost","root","pw");
if (!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'my_database');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
?>
First of all in your login PHP code, you only started a session but you didn't tell the from where to direct to if login is successful. Add a header to the code. That is;
if ($count == 1){
$_SESSION['username'] = $username;
header("Location: page.php"); //the page you want it to go to
}
And your registration PHP code looks ok. Check your database table if you've misspelt anything there.
Your logic to set the $_SESSION['username'] requires that the username and password combination exists once in your database.
This might sound silly but can you confirm that this is the case (i.e. confirm that you have not created the same username and password combination).
Altering the logic to be > 1 would also get around this temporarily. So your code
if ($count == 1){
$_SESSION['username'] = $username;
}
should become
if ($count > 1){
$_SESSION['username'] = $username;
}
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
}