Displaying specific data from mySQL using sessions IDs - php

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
}

Related

PHP display first and last name of logged in user [duplicate]

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

Password hashing within PHP not working

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

Session is not kept/destroyed when i navigate to other pages

Good day.SO i am having an issue in that, when i create a session via a login and a user is authenticated, once i leave that page to say a different page, i am not whether the session is destroyed or not created in the first place, i require this page to hold the session so i can be able to query the users email from it, and use it to query the database to determine the username.
This is my submit.php, called once the user clicks login on the page.
<?php
session_start();
require_once('connect.php');
if(isset($_POST) & !empty($_POST)){
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password =$_POST['password'];
$sql = "SELECT * FROM `USERS` WHERE EMAIL='$email' AND ENCRYPTEDPWD='$password'";
$result = mysqli_query($connection, $sql);
$count = mysqli_num_rows($result);
if($count == 1){
$_SESSION['email'] = $email;
header("Location: Landing page.php");
exit();
}
else{
header("Location: customerportal.php?login=invalid");
exit();
}
}
?>
it redirects to the next page, the landing page.
This page should check email from the session, and then display a username.
<?php
session_start();
$_SESSION['email'] = $email;
$sql = "SELECT * FROM users WHERE EMAIL='$email';";
$result = mysqli_query($connection,$sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0){
while($row = mysqli_fetch_assoc($result)){
echo $row['username'];
}
}
else{
echo "No User.";
}
?>
Please help.
You have an issue with the landing page in below line:-
$_SESSION['email'] = $email;// here you are assigning to SESSION
It needs to be:-
$email = $_SESSION['email'];//assign value from SESSION to variable
So code needs to be like this:-
$email = $_SESSION['email'];
$sql = "SELECT * FROM users WHERE EMAIL='$email'";
Note:- Your code is wide-open for SQL INJECTION. Try to use prepared statements to prevent it.
mysqli::prepare
In your landing page, invert the line after session_start(): You are assigning an empty variable to overwrite your already saved session variable
$email = $_SESSION['email'];
If your query causes you problems after that, try concatenating $email
$sql = "SELECT * FROM users WHERE EMAIL='".$email."';";

Using a reset button to return to the login page in php

This is the code that I currently have. This is redirecting to a page that tells the user that the login information is incorrect. Upn submission of the UN/PW would it be better for it to stay on the login page with error script, and if so how would I do that?
<?php
session_start();
include 'dbConnection.php';
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
$sql = "SELECT * FROM userdb WHERE uid='$uid' and pwd='$pwd'";
$result = mysqli_query($conn, $sql);
if (!$row = mysqli_fetch_assoc($result)) {
echo "Your username or password is incorrect!";
echo "Please try again!"."<br><br>";
echo "<button type='reset'>RESET";
if (isset($_POST['reset'])) {
header("Location: login.php");
echo "</button>"; }
}else {
$_SESSION['id'] = $row['id'];
}
Here is a bump in the right direction. $db below replaces your $conn included from dbConnect.php and
returns an instance of the mysqli class.
<?php
session_start();
$db = new mysqli('db_host', 'db_user', 'db_password', 'db_name');
$stmt = $db->prepare('SELECT * FROM userdb WHERE uid = ? and pwd = ?');
$stmt->bind_param('ss', $_POST['uid'], $_POST['pwd']);
$stmt->execute();
if ($row = $stmt->fetch_assoc()) {
header('Location: login.php?error=1');
exit;
}
$_SESSION['id'] = $row['id'];
header('Location: account.php');
This assumes you ahve 3 pages:
login.php - displays your form and errors. Use the error=1 querystring on login.php to conditionally display an invalid credentials error.
doLogin.php - the login.php page posts here. This handles the login attempt.
account.php - the page you redirect to with a successful login.
Let doLogin.php be responsible for one thing; performing the login.
Let login.phpbe responseible for one thing; presenting the user with the state of their login attempt.

phpMyAdmin user levels

I found this tutorial to create a members only area on my webpage using phpMyAdmin. The only problem I have is I need to have different pages show for different user levels. Currently all my users are user level 0, I would like to create an admin user as user level 1. I believe the php file I need to change is the one below, it is my checkuser.php file. Any help or direction would be much appreciated! Thanks in advance.
<?
/* Check User Script */
session_start(); // Start Session
include 'db.php';
// Conver to simple variables
$username = $_POST['username'];
$password = $_POST['password'];
if((!$username) || (!$password)){
echo "";
include 'loginError.php';
exit();
}
// check if the user info validates the db
$sql = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password' AND activated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_array($sql)){
foreach( $row AS $key => $val ){
$$key = stripslashes( $val );
}
// Register some session variables!
session_register('first_name');
$_SESSION['first_name'] = $first_name;
session_register('last_name');
$_SESSION['last_name'] = $last_name;
session_register('email_address');
$_SESSION['email_address'] = $email_address;
session_register('special_user');
$_SESSION['user_level'] = $user_level;
mysql_query("UPDATE users SET last_login=now() WHERE userid='$userid'");
header("Location: /restricted/index.php");
}
} else {
echo "";
include 'loginError.php';
}
?>
Simple if
session_start();
if($_SESSION['user_level']==0){
header('location: no-access.php');
}
This will redirect user with level zero to no-access page. Put this top of page you want to restrict.

Categories