Displaying username after they have logged in (newbie) - php

Hello im completely new to php and my question is how can i echo out the username of the person who has logged in, on the page they get sent to after logging in successfully?
ive got the login system working and everything but not sure where to write the session stuff etc.
This is my login2a.php
$username = $_POST['username'];
$password = $_POST['password'];
$conn = mysqli_connect('localhost', 'root', '', 'assign02');
$username = mysqli_real_escape_string($conn, $username);
$query = "SELECT password, salt
FROM members
WHERE username = '$username';";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) == 0) // User not found. So, redirect to login_form again.
{
header('Location: login.html');
}
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
//check to see if the password is wrong if wrong redirect user to login forma again and if correct redirect to
if($hash == $userData['password'])
{
header('Location: signed_in.php?username = $username ');
//header('Location: login.html');
}else{ // Redirect to home page after successful login.
//header('Location: signed_in.php?username=$username');
header('Location: login.html');
}
?>
This is the page that i want their username to be displayed, this is just some parts of the website because its too big, what ive echoed is completely wrong i know but hope someone could help me with this problem. This page is the signed_in.php
<div class="layout-978">
<img id="content_background" src="Images/Background.png" />
<div class="main_content">
<div id="top_sellers_title">
<div class="col7">
<!--username displayed to show logged in-->
<?php
if (isset($_SESSION['username'])){
echo "<div id=\"welcome_msg\"> $username </div>";
}
?>

Modify this in your login page and don't forget to use session_start(); at the very beginning of your login page.
if($hash == $userData['password'])
{
$_SESSION['username'] = $username;
header('Location: signed_in.php');
//header('Location: login.html');
}
Then in signed_in.php page, to display the username just do the following
<?php
if(isset($_SESSION['username'])) echo '<div id="welcome_msg">'.$_SESSION['username']. '</div>';
?>

Use session_start() on top of both login2a.php and signed_in.php.
In your login2a.php file where you've successfully authenticated a user, create a session variable named username and assign the username you've passed to the query to that session variable. Here's how
.
.
.
if($hash == $userData['password'])
{
$_SESSION['username'] = $username;
// Continue with your code
}
Hope my answer helps

Related

How to check if a user is logged in

I have built a login php form for an internal website I'm building for our intranet. I am going to combine a few different websites together under one login system. I want to see how I could check if a user is logged in if they visit one of the url's directly and if they're not logged in then redirect them to the login page then after successfully logging in redirect back to the initial page.
I have logged their username and password into a cookie. I know this isn't secure, but again this is just an in house website on the companies intranet. So I don't need much security. The log in system is to just track what each user is doing.
Here's my login code, but now I need to figure out how to check if a user is logged in or not on separate web pages.
//get info from login form
if(isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$rememberme = $_POST['rememberme'];
$username = mysqli_real_escape_string($connection, $username);
$password = mysqli_real_escape_string($connection, $password);
//query users table
$query = "SELECT * FROM users WHERE username = '{$username}' ";
$select_user_query = mysqli_query($connection, $query);
if(!$select_user_query) {
die("Query failed" . mysqli_error($connection));
}
//loop through user info and assigning to variables
while($row = mysqli_fetch_array($select_user_query)) {
$db_id = $row['user_id'];
$db_username = $row['username'];
$db_password = $row['user_password'];
$db_firstname = $row['user_firstname'];
$db_lastname = $row['user_lastname'];
$db_role = $row['user_role'];
}
//validate username and password
if($username === $db_username && $password === $db_password) {
//create cookie to remember user
if(isset($rememberme)) {
//set cookie to last one year
setcookie('username', $_POST['username'], time()+60*60*24*365, '/', 'localhost');
setcookie('password', md5($_POST['user_password']), time()+60*60*24*365, '/', 'localhost');
} else {
//cookie expires when browser closes
setcookie('username', $_POST['username'], false, '/', 'localhost');
setcookie('password', md5($_POST['user_password']), false, '/', 'localhost');
}
//if user exists send to dashboard
$_SESSION['username'] = $db_username;
$_SESSION['user_firstname'] = $db_firstname;
$_SESSION['user_lastname'] = $db_lastname;
$_SESSION['user_role'] = $db_role;
header("Location: ../dashboard.php ");
} else {
header("Location: ../index.php");
}
}
Here is how to check if a user is logged in and then redirect them to the page they first visited.
First check to see if a user is logged in:
<?php
session_start();
if(!(isset($_SESSION['username'])))
{
header("Location: index.php");
}
?>
Then include that file in all of your web pages you will be using. Also, create a session for the URL. This will go at the top of your page:
<?php include "includes/login-check.php"; ?>
<?php $_SESSION['url'] = $_SERVER['REQUEST_URI']; ?>
<?php ob_start(); ?>
Then right in the body of the HTML add this:
<input type="hidden" name="redirurl" value="<? echo $_SERVER['HTTP_REFERER']; ?>" />
Then within your login file check for the URL session:
//check to see what page user first visited
if(isset($_SESSION['url'])) {
$url = $_SESSION['url'];
} else {
$url = "../index.php";
}
//redirect user to page they initially visited
header("Location: $url");
That should fully answer your question.
Create a file which you should include at the top in every file of your system and add the following code
session_start();
if(!(isset($_SESSION['username'])))
{
header("Location:login.php")
}

How to make logout page that involves session cookie using php?

I want to create a logout.php so that it remembers the username from the login.php.
I want to use $_GET method so that it gets the session username from login and when we logout, the cookie session is logged out. And if there is no set cookie session then there will be an error saying no ones were logged in so log gout doesn't work.
The login.php does login's the user and set cookie which I checked from the browser settings.
login.php
<?php
require"connection.php";
if (!isset($_POST['submit'])){
$user = $_POST['username'];
$password = $_POST['password'];
if ($user){
if ($password){
setcookie('username', '$user', time()+3600);
setcookie('password', '$password', time()+3600);
//make sure login info correct
$query = mysql_query("SELECT * FROM users WHERE username = '$user'");
$numrows = mysql_num_rows($query);
if ($numrows == 1) {
$row = mysql_fetch_assoc($query);
$dbuser = $row['username'];
$dbpass = $row['password'];
echo '<script type="text/javascript">alert("Welcome, '.$user.'. A cookie session has been created.");</script>';
}else{echo "Please enter valid username or password";}
}else {echo "Your password didn't match. Please try again";}
}else {echo "Your username didn't match. Please try again";}
}else {echo "Please enter username and password";}
?>
try something like this..
if(isset($_COOKIE['username']) && !empty($_COOKIE['username'])) {
// Bye $_COOKIE['username'], you are logged out.
setcookie('username', '', time() - 3600);
} else {
// no user logged in
}

php session login issue

I have a this login script:
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
include 'includes/connect.php';
$username = mysqli_real_escape_string($con, $username);
$query = "SELECT password, salt
FROM member
WHERE username = '$username';";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result) == 0)
{
header('Location: login.html');
}
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
$_SESSION['username']=$username;
if($hash != $userData['password'])
{
header('Location: login.html');
}else{ // Redirect to home page after successful login.
$_SESSION['username']=$username;
header('Location: stats.php');
}
?>
then this is stats.php:
<?php
session_start();
if(!isset($_SESSION['username'])){
header("Location:register.html");
}
?>
and under this is my html 5 document.
however it doesnt matter if im logged in or not and it still allows me to access stats.php
You are not storing any session value so if condition will always fail.
So Add
$_SESSION['username'] = $userData['username'];
inside login.php.
You haven't set a session yet. That's why you are getting redirected.
Set a session here on your login.php code like this
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
//Set here like this
$_SESSION['username']=$username; // or whatever you have
you always set the username sesion var . Imagine this situation:
I wanna get the users stats , i only need test login with user and try again with other username .
if i write success one time the user name without the correct password , the result of query get a num_Rows > 0 , because the username is ok .
the next step you are going to test the password but between generate hash and test hash you init the sesion.Now my password is wrong but i get init sesion with the username. ????
if know the url to stats i could acces by http url and see the info that isn t mine.
Your structure to login has got a big bug.
You need insert the set session var inside check password. before header ... stats.php and remove the others occurs on login.php document.
you can make this to logout on logout.php : sesion_Destroy()

Losing session values after header redirection

I'm using $_SESSION to keep my users logged in after they have logged in.
When they return to the homepage, they at first appear to be logged in, but after refreshing the page once, they are no longer logged in.
NOTE: I'm still learning PHP programming so please don't mind that most of my code is rather, noobish.
Index.php Code:
<?php
session_start();
$UserOnline = "Guest";
if (isset($_SESSION['username'])) {
$UserOnline = $_SESSION['username'];
}
echo $UserOnline;
?>
Login.php Code:
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username)) {
$InvalidLogin = "Please submit a username";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
} elseif (empty($username)) {
$InvalidLogin = "Please submit a password";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
}
require 'required/connect.php';
$result = mysqli_query($con, "SELECT * FROM users WHERE username='$username'");
$row = mysqli_fetch_array($result);
if ($password == $row['password']) {
$_SESSION['username'] = $username;
echo "Successful Login!";
echo "<br>";
echo "<a href='index.php'>Return to HomePage?</a>";
} else {
$InvalidLogin = "Your info didn't match ours!";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
}
?>
I have tested on the login.php page if the user is in a session there, and I always get the correct return value. The issue is that after I refresh once on the Index.php page, the user is no longer in a session.
Is there something I'm forgetting, or am I not using the $_SESSION correctly? Is there another error that I simply do not know about?
Put exit; after header('location:.....') and your problem will be solved.
Issue is resolved. Error was found in Index.php. Set Variable $UserOnline before the if(isset($_SESSION['username'])). Thanks for the help guys

How to prevent browser from going back to login form page once user is logged in?

I'm trying to make a website in which the admin can upload books through an admin portal. I've made a successful login but when the user gets logged in and presses the back button (on the browser) the form page appears again, and the same happens when they log out and press back button, the page that should appear only appears after they login again. I searched a lot on the internet but all in vain. Please make a suggestion about it.
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username && $password) {
$connect = mysqli_connect("localhost", "root", "") or die ("Could'nt connect to database!"); //database connection
mysqli_select_db($connect, "mahmood_faridi") or die ("Could'nt find database");
$query = ("SELECT * FROM user WHERE username= '$username'");
$result = mysqli_query($connect, $query);
$numrows = mysqli_num_rows($result);
if ($numrows !== 0) {
while ($row = mysqli_fetch_assoc($result)) {
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($username == $dbusername && $password == $dbpassword) {
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header('location: help.php'); //another file to send request to the next page if values are correct.
exit();
} else {
echo "Password Incorrect";
}
exit();
} else {
die("That user doesn't exists!");
}
} else {
die("Please enter a username and password");
}
?>
On the login screen, in PHP, before rendering the view, you need to check if the user is already logged in, and redirect to the default page the user should see after logged in.
Similarly, on the screens requiring login, you need to check if the user is not logged in and if not, redirect them to the login screen.
// on login screen, redirect to dashboard if already logged in
if(isset($_SESSION['username'])){
header('location:dashboard.php');
}
// on all screens requiring login, redirect if NOT logged in
if(!isset($_SESSION['username'])){
header('location:login.php');
}
You can conditionally add Javascript code to go forward to the intended page.
<script>
history.forward(1);
</script>
This might be annoying or fail when Javascript is not present and/or disabled.
index.php page you should need to add the code in the top of a php file....
<?php
include 'database.php';
session_start();
if (isset($_SESSION['user_name'])) {
header('location:home');
}
if (isset($_POST['submit'])) {
$user = $_POST['user_name'];
$password = $_POST['password'];
$query = "select count(*) as count from users where user_name= '$user' and password = '$password';";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
while ($row = mysqli_fetch_assoc($result)) {
$count = $row['count'];
if ($count == 1) {
$_SESSION['user_name'] = $user;
header('location:home');
}
}
}
?>
This is another page. home.php page you should need also to add the code in the top of a php file to check it first.
<?php
include 'database.php';
if (!(isset($_SESSION['user_name']))) {
header('location:index');
}
?>
I am just modifying #sbecker's answer, use exit() after redirecting.
I have faced the same issue, but now exit(); works for me.
// on login screen, redirect to dashboard if already logged in
if(isset($_SESSION['username'])){
header('location:dashboard.php');
exit();
}
// on all screens requiring login, redirect if NOT logged in
if(!isset($_SESSION['username'])){
header('location:login.php');
exit();
}
you can use this it's easy to use
<?php
if(empty($_SESSION['user_id'])){
header("Location: login.php");
}
else{
header("Location: dashboard.php");
}
?>
My suggestion: the login should happen when the users clicks some link/button
Once the login server side takes place, use the the php function header('url') to redirect the user to the url it should be. (be careful not to echo anything otherwise the redirect will not happen)
[Edit] You say you have the first login file an html one, that is fine to me, but you say it redirects to whatever, then you are using a redirect from client side. In my opinion you should not use that client side redirect for the login. Probably that is causing the confusion.

Categories