How to check if a user is logged in - php

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")
}

Related

Php Session Redirect Page

Okay, What I have here is a simple php login session. Sometimes session destroy even I don't destroy the session. In my Index.php, there's a link for editing record. My problem is, if session destroy and I click edit, the page open's in modal or fancybox and shows login.php and after I login it's goes to index.html. What I need to do is instead of going into index.html, I need to redirect to edit.php with GET value to continue the edit process. Any help?
Index.php
<a class="fancybox" href="edit.php?pn='.$row["id"].'"><img src="images/edit.png"></a>
Edit.php
<?php
session_start();
include('connect.php');
$tbl_name="login_admin";
if(! isset($_SESSION['id'])){
header('location:login.php');
exit;
}
$id = $_SESSION['id'];
$sql = $mysqli->query("SELECT * FROM $tbl_name WHERE username='$id'");
$accounts = $sql->fetch_assoc();
$term= $mysqli->real_escape_string($_GET["pn"]);
?>
Login.php
<?php
require_once('connect2.php');
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$submit = $_POST['submit'];
if($username && $password){
$sql = sprintf("SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'");
$result = #mysql_query($sql);
$accounts = #mysql_fetch_array($result);
}
if($accounts){
$_SESSION['id'] = $accounts['username'];
header("location:index.html");
exit;
}elseif($submit){
$msg = 'Invalid Username or Password';
}
?>
Unfortunately you can't continue the edit process, but you can redirect user to edit page after login.
There are more ways how to to it, I will show one of them.
before redirecting user to login script, save his original URL to session (another way would be to pass it to login.php as GET parameter - don't forget validation in that way):
Edit.php:
<?php
session_start();
include('connect.php');
$tbl_name="login_admin";
if(! isset($_SESSION['id'])){
$_SESSION['original_url']=$_SERVER['REQUEST_URI']
header('location:login.php');
exit;
}
// rest of the code.....
Then redirect user to that page instead of default index.html page
Login.php:
<?php
require_once('connect2.php');
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$submit = $_POST['submit'];
// Security note: see I've sanitized $username and $password with mysql_real_escape_string() to avoid SQL injection
if($username && $password){
$sql = sprintf("SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'");
$result = mysql_query($sql);
$accounts = mysql_fetch_array($result);
}
// when account was found store identity to session
if($accounts){
$_SESSION['id'] = $accounts['username'];
if (isset($_SESSION['original_url']) {
// if user came from internal url, redirect to it and remove it from session
$originalUrl = $_SESSION['original_url'];
unset($_SESSION['original_url']);
header("location:".$originalUrl);
exit;
} else {
// redirect user to default page after login
header("location:index.html");
exit;
}
} elseif($submit){
// login form was sent, but user with given password not found
$msg = 'Invalid Username or Password';
}
?>

Displaying username after they have logged in (newbie)

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

PHP session_start question

So i'm writing a simple login script and I ran into some problems. I was able to create the login.php file that works with this dashboard.php file below. Let me describe the scenario: User come into the main page, which is the login page. Enters username and password. If entered correctly user will see the output "dashboard succesfull". If entered wrongly it will redirect them to loginfailed.php. Problem is that the browser does not remember that the user has already been logged in. If I re-enter this page, it will directly goes to loginfailed.php. So my obivous n00b question here is......is there a way to make the browser remember that the user has already been logged in?
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$dblink = mysql_connect("localhost", "root", "");
mysql_select_db("user",$dblink);
$sql = "select * from members where username = '$username' and password = '$password'";
$result = mysql_query($sql) or die ( mysql_error() );
$count = 0;
while ($line = mysql_fetch_assoc($result)) {
$count++;
}
if ($count == 1) {
$_SESSION['loggedIn'] = "true";
echo "<a href='dashboard.php'>dashboard succesfull</a>";
} else {
$_SESSION['loggedIn'] = "false";
header("Location: loginfailed.php");
}
?>
Sure. You just need to put, at the top of the page but below session_start(), something like:
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == 'true') {
# do something. maybe redirect and then exit?
}
Also, I'd suggest using a session name and escaping the username and password before putting them in your SQL.

User login using PHP

I haven't been able to trace what's wrong with this code. I am trying to login the user by taking his username and password. Here is what I am trying to do.
index.php:
This file checks if the username cookie is set and displays the file accordingly. This file submits the username and password to a file called validate.php.
validate.php:
<?php
session_start();
include("connector.php");
$var=connect();
if($var==10)
{
$valid=false;
$row= mysql_query('select * from users where username="'.$_POST["username"].'"');
if($row['password']==$_POST["password"])
$valid=true;
if($valid)
{
$_SESSION["username"]=$_POST["username"];
$_SESSION["userid"]=$row['userid'];
echo "<script>document.location.href='./session_creator.php'</script>";
}
else
{
echo "invalid";
}
}
?>
connector.php==>
<?php
$connection=0;
function connect()
{
$dbc = mysql_connect('localhost:3306','root','root');
if (!$dbc)
{
die ('Not connected:'. mysql_error());
return -10;
}
else
{
$connection = mysql_select_db("citizennet",$dbc);
if(!$connection)
{
die("Not connected: ". mysql_error());
return -20;
}
}
return 10;
}
?>
session_creator.php:
<?php
session_start();
setcookie("username",$_SESSION['username'],time()+3600);
setcookie("userid",$_SESSION['userid'],time()+3600);
echo "<script>document.location.href='./index.php'</script>";
?>
the redirected index.php file reports that the cookie is not set. I am newbie, please correct me if the process I am following is wrong.
I am adding index.php that verifies if the user is logged in:
<?php
if(!isset($_COOKIE["username"]))
echo '<a id="login_button">login</a> <div id="login_box_pane"><form action=validate.php method="post">Username: <input type="text"/> Password:<input type="password"/><input type="submit"/></form></div>';
else
echo "<a>".$_COOKIE["username"]."</a>";
?>
When you set your cookie on your page it should be like this:
<?php //login page
session_start()
$username = $_POST['username'];
$password = $_POST['password'];
/*
Check authentication with database values
*/
//if login successful set whatever session vars you want and create cookie
$_SESSION['username'] = $username;
setcookie($username, $password, time()+3600);
?>
Prior to this you will have check the users credentials and log them in or deny them. Once logged in you set the session variables. Then to create the cookie you use the code above.
$user = mysql_real_escape_string($_POST['user']);
$pass = mysql_real_escape_string($_POST['pass']);
$sql = "SELECT * FROM users WHERE username='$user' AND password='$pass'";
$result = mysql_query($sql);
That will take care of your sql injection vulnerabilities and also get you the correct account only if both the username and password are correct
Now you can use your conditions to set the cookies and sessions

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