How to Check If a User Is Logged-In in PHP

How to check if a user is logged in

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.

PHP: How to check if user is already logged in and otherwise redirect to login page

Update: The question has been resolved in chat.


As per your edit, change this block:

<!DOCTYPE html>
<html>
<head>
<?php
define("someUnguessableVariable", "anotherUnguessableVariable");
session_start();
if(!(isset($_SESSION['login']) && $_SESSION['login'] != '')){
header ("Location: login.php");
}

to:

<?php 
session_start();
?>

<!DOCTYPE html>
<html>
<head>
<?php
define("someUnguessableVariable", "anotherUnguessableVariable");

if(!isset($_SESSION['login']) && $_SESSION['login'] != ''){
header ("Location: login.php");
exit; // stop further executing, very important
}
  • Follow the same structure for starting the session in all your files using sessions.
  • Make sure that your file does not have a byte order mark (BOM).
  • No space before <?php etc. this has already been established in comments.

Using a code editor such as Notepad++ https://notepad-plus-plus.org/ and to save it as UTF-8 without BOM which will ensure there is no byte order mark.

Also, using the new method for your sessions array check.

if(!isset($_SESSION['login']) && $_SESSION['login'] != ''){

Also check to see that none of your included/required files have the same issues, including login.php.


Footnotes:

Inside Notepad++'s dropdown menu, you will see

  • Encoding. It will show you what the present file's encoding is set to.

If it does show a byte order mark, follow these steps:

  1. Click on "Encoding".
  2. Convert to UTF-8 without BOM
  3. Save the file.
  • Do this for all your files.

Reference(s):

  • How to fix "Headers already sent" error in PHP

Sidenote:

You should change $stmt->execute(); to

if(!$stmt->execute()){
trigger_error("there was an error....".$conn->error, E_USER_WARNING);
}
  • It's better to catch possible errors in your query.

PHP-Script to check if user is logged in not working as expected

Your going to want to update

if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] !== true){

with

if(!isset($_SESSION["loggedin"]) || !$_SESSION["loggedin"]) {

That verifies that the $_SESSION["loggedin"] is not set OR that its set and NOT TRUE then it will do your redirection

How can I verify if the user is logged in? I need to show stuff only if users are loged in.This is the code Im using

You can change your code like shown below

@auth
content if user is logged in
@endauth

@guest
content if user is not logged in
@endguest

check if user is logged in and then check if user was logged in with a radio button checked

You just assign a new session variable that you check when displaying pricing:

<?php
require('db.php');
if (isset($_POST['username'])){
$username = stripslashes($_REQUEST['username']);
$username = mysqli_real_escape_string($con,$username);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
$query = "SELECT * FROM `users` WHERE username='$username' and password='".md5($password)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
$_SESSION['view_type'] = (!empty($_POST['corporate']))? 'c' : 'b';
header("Location: index.php");
exit;
}else{
echo "<div class='form'><h3>Username/password is incorrect.</h3><br/>Click here to <a href='login_page.php'>Login</a></div>";
}
} else { ?>...etc.

To use the variable, it would be wise to make a function or two so you are not repeating yourself over and over with a bunch of if/else:

# Checks if user is corporate
function isCorporate()
{
return (isset($_SESSION['view_type']) && $_SESSION['view_type'] == 'c');
}
# Checks if user is birthday
function isBirthday()
{
return (isset($_SESSION['view_type']) && $_SESSION['view_type'] == 'b');
}
# Checks if user is logged in at all
function isLoggedIn()
{
return (!empty($_SESSION['username']));
}

So you would do something like:

# Logged In?
if(isLoggedIn()) {
# What kind of login?
echo (isCorporate())? 'Higher value' : 'Lower value';
}
else
# Not logged in...
echo 'Log in to see price!';

Check against $_SESSION['view_type'] when deciding the price view.

To just have the view type only, you can use either same form with a checkbox that if checked, will allow your logic to ignore the username and password fields you can have a separate form with those, you could have a couple of style <a> links that look like radio button, etc. There are many ways you can make the session create the view without logging in the user fully.

Couple side notes, you should not escape the user submissions, you should be binding parameters instead. By binding parameters, it means you don't put your variables right into the sql statement like you have now. Secondly, you should be using password_hash() / password_verify() for storing and retrieval of password hash. md5() is not sufficient for security. Lastly add exit after you redirect using header(), it will stop any further execution of the script, even if there is nothing after, it's good habit to do so.

One note about the functions, you need only store them in an includable file and just use require_once('myfunctions.php'); to include them at the top of the page.


EDIT:


So based on your code snippet from the comment:

<?php
if(isset($_SESSION['username'])){ ?>
<p>Pricing below:</p>
<?php if(isCorporate()) { ?>
<h1>$100</h1>
<?php } elseif(isBirthday()) { ?>
<h3>$50</h3>
<?php } else { ?>
<p><em>NOT SET YET</em></p>
<?php } ?>
<p><a class="link" href="logout.php" style="text-decoration:none">Logout</a></p>
<?php } else { ?>
<a class="link" href="login_page.php" style="text-decoration:none">login</a> or <a class="link" href="registration_page.php" style="text-decoration:none">Register</a>
<?php } ?>


Related Topics



Leave a reply



Submit