0

I want to ensure that an HTML page only appears if the user has logged in. I'm trying to do it by setting a session variable from the login page then checking if that variable exists when the HTML page is loaded.

This is my code at the very top of the HTML page:-

<?php
session_start();
if (!isset($_SESSION['checks'])) {
   header("location: http://localhost/project/fail.php");
}
?>

It doesn't redirect! Nothing happens at all except that the HTML page gets loaded. Can anyone help please?

marcher
  • 11
  • 4
  • Check that your condition is met. If it is, check that no output has been sent prior to calling `header`. And, in any case, enable [proper development-friendly error reporting](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display). – Jeto Oct 25 '20 at 11:41

4 Answers4

0

Thank you all for your helpful suggestions. The snippet I posted shows the very first lines: i.e. session_start(); is the very first line.

By moving the var check snippet from the session_start() segment and making a separate php check snippet immediately after the body tag, everything works as expected.

marcher
  • 11
  • 4
-1

make sure that session_start() always come at the first line

    if(!isset($_SESSION['checks'])){
        header('location: fail.php');
    }

Umair Mubeen
  • 823
  • 4
  • 22
  • I apologise for not making my objective clear enough. I want to be certain that the HTML form is only being accessed from the login page. i.e. I'm trying to prevent it being loaded from cache or from the browser's back button. – marcher Oct 26 '20 at 14:38
-1

You can use header function : https://www.php.net/manual/en/function.header.php

Referring to it :

<?php
session_start();
if (!isset($_SESSION['checks'])) {
   header("Location: http://localhost/project/fail.php");
}
?>
Yvan1263
  • 80
  • 2
  • 14
-1

I believe your problem is on the login page... Although, if I were to talk about this page, consider trying the following code instead of your snippet first. If it gives the desired outcome then you will know that the problem is with your header and not the session:

<?php
session_start();
if (!isset($_SESSION['checks'])) {
  echo "not logged in";
}
?>

Do make sure you're referring to the correct session variable if this code doesn't work and feel free to share how you are starting this session on your login page.

David Buck
  • 3,752
  • 35
  • 31
  • 35