This question already has an answer here:
PHP display name of login user
(1 answer)
Closed 1 year ago.
I want to display the name of the logged in user, but since there is no field to input name when logging in, the session only gets the email and password values. How can I display name?
my server.php
<?php
include_once "inc/user-connection.php";
session_start();
$name = mysqli_real_escape_string($conn, $_POST['name']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$username = mysqli_real_escape_string($conn, $_POST['username']);
if (isset($_POST['admin-sign-in'])) {
if (!empty($email)) {
if (!empty($password)) {
$sql = 'SELECT email, password FROM admin WHERE email = ?';
// preparing the SQL statement
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$stmt->store_result(); // Store the result so we can check if the account exists in the database.
// If email exists in sign_up table
if ($stmt->num_rows > 0) {
$stmt->bind_result($email, $password);
$stmt->fetch();
// if password user enters matches the one in the database
if (password_verify($password, $hashed_password)) {
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($query);
$_SESSION['name'] = $row['name'];
// upon successful login, redirect user to landing apge
header("location: dashboard.php");
die();
} else {
// Incorrect password
header("location: ../html/sign-in-error.html");
die();
}
} else {
// Incorrect username
header("location: ../html/sign-in-error.html");
die();
}
$stmt->close();
}
} else {
header("location: ../html/404-error.html");
die();
}
} else {
header("location: ../html/404-error.html");
die();
}
}
my dashboard.php
<?php
session_start();
?>
<div class="d-block">
<h1 class="lead fw-normal text-muted mb-4 px-lg-10">Hello, <?php echo $_SESSION['name']; ?></h1>
</div>
sign-in page
Dashboard: should display first and last name but is empty(It can display email, but I don't want that)
The $name variable contains both first and last name, there is only one column for name in the table.
Like commented on your question, when doing the sign in, just fetch the names from the database when you check user login details and to ease your pain you can store these names to your $_SESSION so you can call it whenever you need it if the session is up.
$_SESSION['first_name'] = $name;
Should not be harder than that. Only thing confusing was that you store your sign ups to different table than you use in sign in, but there seems to be admin and user tables seperately.
Offtopic: You could just add column to your users table for like admin with BOOLEAN or rank with actual rank name
Related
I am trying to display the name of a user when they are logged in. My code uses $_SESSIONS to store the name, but since there no input in my login in page, the name doesn't get assign and it ends up being just hello, instead of something like hello, John Smith.
I've tried using sql to select the name by matching the email to the email of the logged in user, and storing that in $_SESSION but it still doesn't print name of user.
my server.php
<?php
include_once "inc/user-connection.php";
session_start();
$name = mysqli_real_escape_string($conn, $_POST['name']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$username = mysqli_real_escape_string($conn, $_POST['username']);
if (isset($_POST['admin-sign-in'])) {
if (!empty($email)) {
if (!empty($password)) {
$sql = 'SELECT email, password FROM admin WHERE email = ?';
// preparing the SQL statement
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$stmt->store_result(); // Store the result so we can check if the account exists in the database.
// If email exists in sign_up table
if ($stmt->num_rows > 0) {
$stmt->bind_result($email, $password);
$stmt->fetch();
// if password user enters matches the one in the database
if (password_verify($password, $hashed_password)) {
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($query);
$_SESSION['name'] = $row['name'];
// upon successful login, redirect user to landing apge
header("location: dashboard.php");
die();
} else {
// Incorrect password
header("location: ../html/sign-in-error.html");
die();
}
} else {
// Incorrect username
header("location: ../html/sign-in-error.html");
die();
}
$stmt->close();
}
} else {
header("location: ../html/404-error.html");
die();
}
} else {
header("location: ../html/404-error.html");
die();
}
}
my dashboard.php
<?php
session_start();
?>
<div class="d-block">
<h1 class="lead fw-normal text-muted mb-4 px-lg-10">Hello,
<?php
echo $_SESSION['name'];
?>
</h1>
</div>
You did not select the name and you are fetching it.
$sql = 'SELECT email, password, name FROM admin WHERE email = ?';
or
$sql = 'SELECT * FROM admin WHERE email = ?';
should fix the issue.
Additional: you can remove all your else statements since all of it will give the same result.
<?php
include_once "inc/user-connection.php";
session_start();
$name = $_POST['name'];
$password = $_POST['password'];
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$email = $_POST['email'];
$username = $_POST['username'];
if (isset($_POST['admin-sign-in'])) {
if (!empty($email)) {
if (!empty($password)) {
$sql = 'SELECT * FROM admin WHERE email = ?';
// preparing the SQL statement
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$stmt->store_result(); // Store the result so we can check if the account exists in the database.
// If email exists in sign_up table
if ($stmt->num_rows > 0) {
$stmt->bind_result($email, $password, $name);
$stmt->fetch();
// if password user enters matches the one in the database
if (password_verify($password, $hashed_password)) {
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($query);
$_SESSION['name'] = $row['name'];
// upon successful login, redirect user to landing apge
header("location: dashboard.php");
die();
}
}
$stmt->close();
}
}
}
header("location: ../html/404-error.html");
die();
}
I'm trying to create a password hash in a php file for a mini blog i'm creating, I have got to the stage where new user passwords are being hashed when a user registers, but when I test the new user login, i get an incorrect password error. Here is the code:-
<?php
//require the public header which starts a session and connects to the database
require('header_public.php');
//3. If the form is submitted or not.
//3.1 If the form is submitted
if (isset($_POST['username']) and isset($_POST['password'])){
//3.1.1 Assigning posted values to variables.
$username = db_escape($con, $_POST['username']);
$password = db_escape($con, $_POST['password']);
//3.1.2 Checking the values are existing in the database or not
$query = "SELECT * FROM user WHERE username='$username'";
$result = mysqli_query($con, $query) or die(mysqli_error($con));
$resultPassword = mysqli_query($con, $query) or die(mysqli_error($con));
$count = mysqli_num_rows($result);
//getting the hashed password from the database
while ($row=mysqli_fetch_array($resultPassword)){
$hashPassword = $row['password'];
}
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1 && password_verify($password, $hashPassword)){
$_SESSION['username'] = $username;
//Get the user type for use in other areas of the site
while ($row=mysqli_fetch_array($result)){
$admin = $row['admin'];
}
//assign userid to session array
$_SESSION['admin'] = $admin;
}else{
//3.1.3 If the login credentials doesn't match, he will be shown with an error message.
$fmsg = "Invalid Login Credentials.";
}
}
if (isset($_SESSION['username'])){
//$username = $_SESSION['username'];
echo "Welcome back " . $username;
echo " </br> You will be redirected to the members area in less than 5 seconds";
header( "Refresh:3; summary_page.php");
echo "</br> <a href='logout.php'>Logout</a>";
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
?>
Grateful for any steer someone could provide. I think the issue is related to the starting the new session with the username, but can't be sure
I have a problem with multi-level user login in PHP MySQL. I already have a code but the user still can access the admin site, what's the problem with my code? still, I do have a problem with the session of admin and user acct. thank you! here's my code.
require('db.php');
session_start();
if (isset($_POST['username'])){
$account = stripslashes($_REQUEST['account']);
$account = mysqli_real_escape_string($con,$account);
$username = stripslashes($_REQUEST['username']); // removes backslashes
$username = mysqli_real_escape_string($con,$username); //escapes special
characters in a string
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM users_detail WHERE account = '$account',username=
'$username' and password= '$password' ";
$result = mysqli_query($con,$query);
$rows = mysqli_num_rows($result);
if($account == "admin" && $rows['username'] = $username &&
$rows['password']=$password){
$_SESSION['username'] = $username;
header("Location: index.php"); // Redirect user to index.php
}
if($account == "user" && $rows['username'] = $username &&
$rows['password']=$password){
$_SESSION['username'] = $username;
header("Location: add user.php"); // Redirect user to index.php
}else{
echo " <div class='alert'>
Username/password is incorrect. Click <a href = 'login.php'>here</a> to log-in.
</div> ";
}
}else{
?>`
here is the full solution,
1 , in your user table you need to create a column call user_role
every user in the table either admin or normal_user
2 in your log.php , first fetch data base get the user_role value , when you verify user password and db password , save as session .
<?php
if( isset($_POST['login_btn'])){ // someone click login btn
$username = clean($_POST['username']);
//clean is the custom function to remove all harmful code
$password = clean($_POST['password']);
// run query to get db username & password i am using prepare stmt for more secure , you can use mysqli_fetch_array , but need to implement mysql_real_escape_string for sql injection
$stmt = mysqli_prepare($connection,"SELECT username,password,email,user_role FROM your table WHERE username = ? ");
//$connection is your db connection
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $bind_username,$bind_password,$bind_email,$bind_user_role);
confirm($stmt); // confirm is also custom function to check query is successful execute
while (mysqli_stmt_fetch($stmt)) {
$db_username = $bind_username;;
$db_password = $bind_password ;
$db_email = $bind_email ;
$user_role = $bind_user_role ;
}
// do form validation
if($username =="" or $password =="" ){
echo 'All Fileds Are Required';
}elseif( $username !== $db_username ){
echo 'username not existed';
}else{
if( password_verify($password, $db_password)){
// assuming your using password_hash function to verify , or you can just use simply compare $password == db_password
// if password_verify return true meaning correct password then save all necessary sessions
$_SESSION['username'] = $db_username ;
$_SESSION['user_email'] = $db_email ;
$_SESSION['user_role'] = $user_role ;
// first method -> header('Location: portal.php');
// you can now direct to portal page{1st method } where all admin or normal user can view
// or you can now do separate redirection (2nd method below )
// remember $user_role will == 'admin' or 'normal_user'
if( $user_role == 'admin' ){
header('Location: page_admin_will_view.php');
}elseif( $user_role == 'normal_user' ){
header('Location: page_normal_user_will_view.php');
}
}else{
echo 'incorrect password';
}
}
} // end of post request
?>
3 how about normal user accidentally visit the admin page ?
we have consider this and do some extra work
put below code in the page_admin_will_view.php header
<?php
if( isset($_SESSION['user_role'] )){
// meaning user is logged in
if( $_SESSION['user_role'] !== 'admin'){
// meaning user_role is not amind , redirect to the page normal user belongs to
header("Location: ../normal_users.php");
}
} else{
//redirect to somewhere meaning user is not logged in
header("Location: ../somewhere.php");
}
?>
I hope this would help you , and I am using it, it may not be a perfect solution. but it works for me. hah
mysqli_num_rows($result) returns the number of rows.
So after $result = mysqli_query($con,$query); you need to write fetch data using mysqli_fetch_array($query)
What you are talking about is RBAC(Role Base Access Control).
if($account == "admin" && $rows['username'] = $username && $rows['password']=$password){
$_SESSION['username'] = $username;
$_SESSION['access'] = $account;
}
And on your pages where you want admin access, probably you should either redirect the user to home or send an UnAuthorised access message.
if(isset($_SESSION['access']) && $_SESSION['access'] != 'admin') {
header("Location: index.php");
}
Also if you are looking for more controlling based on the role I will suggest you to use a library like
http://phprbac.net/
first of all , create admin role like you did with $account
when user login save their admin_role in session ,
$admin_user = $_SESSION['admin_user'] ;
$normal_user = $_SESSION['normal_user'] ;
in admin site , like admin.php , the page you do not want normal user view
write this {perfectly write it in header.php}
if(isset($_SESSION['username'])){
//meaning user is logged in
if(isset($_SESSION['admin_user']) or isset($_SESSION['normal_user'])){
if( $_SESSION['admin_user'] !== 'admin_user' ){
header('Location: somewhere.php');
}
}
}else{
//meaning user is not logged or session had terminated
header('Location: index.php');
}
Seems like you're trying to implement role-based access control on your website.
Here is a possible implementation using prepared statements:
<?php
// db.php should create a mysqli insance:
// $con = new mysqli("host", "username", "password", "databaseName");
require('db.php');
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
//Checking is user existing in the database or not
$query = "SELECT * FROM users_detail WHERE username = ? and password = ?";
//use prepared statement
$stmt = $con->prepare($query);
$stmt->bind_param('ss', $_POST['username'], $_POST['password']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows !== 0) {
//fetch user from database.
$user = $result->fetch_assoc();
//check if user is an admin.
if($user['account'] === "admin") {
$_SESSION['username'] = $username;
header("Location: admin.php"); //admin's page
}
//check if user is a normal user.
if($user['account'] === "user") {
$_SESSION['username'] = $username;
header("Location: user.php"); //user's page
}
} else {
echo '<div class="alert">Username/password is incorrect. Click here to log-in.</div>';
}
//free memory used by the prepared statement.
$stmt->close();
} else {
//username and password not provided.
}
?>
In my database, there is a row called 'role' which is specific the whether it is admin or user for login.
Of course, admin and user have different function.
here is my login process code.
<?php
include 'database_conn.php'; // make db connection
ini_set("session.save_path", "../../sessionData");
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<?php
$username = filter_has_var(INPUT_POST, 'userName') ? $_POST['userName']: null;
$passWD = filter_has_var(INPUT_POST, 'pwd') ? $_POST['pwd']: null;
$username = trim($username);
$passWD = trim($passWD);
//before we query from the database , we have to standartise
// create an empty array
if (empty($username)){
die("No username entered.");
}
if (empty($passWD)){
die("No password entered.");
}
/* Query the users database table to get the password hash for the username entered by the user in the logon form */
$sql = "SELECT password ,userID FROM t_user WHERE username = ?";
$stmt = mysqli_prepare($conn, $sql); // prepare the sql statement
/* Bind the $username entered by the user to the prepared statement. Note the “s” part indicates the data type used – in this case a string */
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);// execute the query
/* Get the password hash from the query results for the given username and store it in the variable indicated */
mysqli_stmt_bind_result($stmt, $passWDHash,$userID);
/* Check if a record was returned by the query. If yes, then there was a username matching what was entered in the logon form and we can now test to see if the password entered in the logon form is the same as the stored (correct) one in the database. */
if (mysqli_stmt_fetch($stmt)) {
$_SESSION['uName'] = $username;
$_SESSION['uID'] = $userID;
//PASSWORD CORRECT
if (password_verify($passWD, $passWDHash)) {
$_SESSION['logged-in'] = true;
echo "<p>Welcome back " .$_SESSION['uName']."</p>\n";
echo "<p>Welcome back " .$_SESSION['uID']."</p>\n";
echo "<p>Password correct!</p>\n";
echo "<p><a href='logout.php'>Logout</a></p>";
}
else {
echo "<p>Password incorrect.</p>\n";
}
}
else {
echo "<p>Sorry we don't seem to have that username.</p>";
}
//this line should determine whether it is user or admin is login
$result = mysqli_query($conn,$sql);
if($result)
{
$row = mysqli_fetch_assoc($result);
$user_type = $row['role']; // you get user type here whether he's admin or login
if ($user_type == 'admin') {
echo " this is admin";
//header to admin page
}
elseif ($user_type == 'user') {
echo "this is user" ;
//header to user page
}
else{
echo "query failed";
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>
</body>
</html>
The code doesn't work as it should show the login role.
it seem like the role cannot be determine
Or is there any other method to do so???
The code doesn't work as it should show the login role. it seem like
the role cannot be determine
well the reason that is happening is because you have undefined index role. this line should throw a notice of undefined index : $user_type = $row['role']; because role is undefined on your sql statement you did not select role. this is your statement : $sql = "SELECT password ,userID FROM t_user WHERE username = ?"; as you can see you don't select role anywhere in your code, also i don't understand what are you trying to achieve here : $result = mysqli_query($conn,$sql);
You have already prepared a statement and executed the statement therefore you don't need to run another query to determine the user's role, this can all be done with a single query.
This is how u can achieve this :
<?php
ob_start();
session_start();
ini_set("session.save_path", "../../sessionData");
include 'database_conn.php'; // make db connection
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$username = filter_has_var(INPUT_POST, 'userName') ? $_POST['userName'] : null;
$passWD = filter_has_var(INPUT_POST, 'pwd') ? $_POST['pwd'] : null;
$username = trim($username);
$passWD = trim($passWD);
//before we query from the database , we have to standartise
// create an empty array
if (empty($username)) {
die("No username entered.");
}
if (empty($passWD)) {
die("No password entered.");
}
/* Query the users database table to get the password hash for the username entered by the user in the logon form */
$sql = "SELECT password ,userID,role FROM t_user WHERE username = ?";
$stmt = mysqli_prepare($conn, $sql); // prepare the sql statement
/* Bind the $username entered by the user to the prepared statement. Note the “s” part indicates the data type used – in this case a string */
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt); // execute the query
/* Get the password hash from the query results for the given username and store it in the variable indicated */
mysqli_stmt_bind_result($stmt, $passWDHash, $userID, $user_type);
/* Check if a record was returned by the query. If yes, then there was a username matching what was entered in the logon form and we can now test to see if the password entered in the logon form is the same as the stored (correct) one in the database. */
if (mysqli_stmt_fetch($stmt)) {
$_SESSION['uName'] = $username;
$_SESSION['uID'] = $userID;
//PASSWORD CORRECT
if (password_verify($passWD, $passWDHash)) {
$_SESSION['logged-in'] = true;
echo "<p>Welcome back " . $_SESSION['uName'] . "</p>\n";
echo "<p>Welcome back " . $_SESSION['uID'] . "</p>\n";
echo "<p>Password correct!</p>\n";
echo "<p><a href='logout.php'>Logout</a></p>";
// check user role
if ($user_type == 'admin') {
echo " this is admin";
//header to admin page
} elseif ($user_type == 'user') {
echo "this is user";
//header to user page
}
} else {
echo "<p>Password incorrect.</p>\n";
}
}
else {
echo "<p>Sorry we don't seem to have that username.</p>";
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>
</body>
</html>
NB: is important that you enable error reporting when you are still
working on your localhost so that you can see these notices and small
errors you are doing : add at the top of your page :
ini_set('display_errors', 1);
`error_reporting(E_ALL);`
And also you must always check your server error logs located in apache/logs/error.log
I'm trying to display the users first name after they login. They login using their email and password. Though, I would like to collect their first name and display it. Their name is in the same table that the email/password are in. Traditionally, I would use a session ID like this below.
<?php
session_start();
$_SESSION['first'] = $first;
?>
But this typically is for submitted data in a form and is used after the form has been authenticated. My question is, how would I gather data from the mySQl table rather than collecting it from the form and be able to have it has a session ID?... if that makes sense
In your script where they login...just fetch the row and store into session...
Im using PDO, because thats much safer than the deprecated mysql_* functions you use in your login example.....
//start the session
session_start();
//Get their credentials, as follows...
$name = $_POST['username'];
$pass = md5($_POST['password']);
$stmt = $db->prepare("SELECT * FROM admin WHERE username=? AND password=?");
$stmt->execute(array($name, $pass));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row > 0 ) {
//Store users info in a session
$_SESSION["username"] = $row["username"];
$_SESSION["firstname"] = $row["firstname"];
$_SESSION["auth"] = "set";
//Redirect to the user area, where you can echo their name
header ("Location: /app");
//Once in the user area, you can just echo their name like so...
//echo "Hello ".$_SESSION['username'].", Welcome to my site";
} else {
//Redirect back to login if their info is incorrect
header('location: /login');
//whatever your login page name might be...
}
But heres the code, if you don't wanna bother changing your site to utilizing PDO...
include("db.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$username=mysql_real_escape_string($_POST['username']);
$password=md5(mysql_real_escape_string($_POST['password']));
$sql="SELECT id, username, firstname FROM admin WHERE username='$username' and passcode='$password'";
$result=mysql_query($sql);
$row = mysql_fetch_row($result);
if(count($row)>0)
{
$_SESSION['auth'] = 'set';
$_SESSION['username'] = $row['username'];
$_SESSION['firstname'] = $row['firstname'];
header ("Location: /app");
}
else
{
$error="Your Hngout credentials are incorrect";
}
}
Select the first name (and any other fields you desire) when checking the user name and password match.
if (!isset($_SESSION)) session_start();
$sql=sprintf("SELECT email, firstname FROM users WHERE email=%s AND password=%s",
$_POST["email"], $_POST["password"]);
//You'd better use parameterized query
$result = mysqli->query($sql);
$row = $result->fetch_assoc();
if(mysqli->num_rows > 0)
{
$_SESSION["email"] = $row["email"];
$_SESSION["firstname"] = $row["firstname"];
}
else
{
//operation for no matches
}