Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am new to PHP and am struggling with the following:

I have a page where I want to check if someone is a registered user before letting them see the content of the site. So my thought was that in my header file (which is referenced on all single pages via require_once("includes/header.php");) I can check on that and redirect them to a login page (login.php) if they have not logged yet.

So here is everything that I have in my header:

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

            include "system/config.php";

            $pageURL = basename($_SERVER["REQUEST_URI"]);
            $pageName = pathinfo(parse_url($pageURL, PHP_URL_PATH), PATHINFO_FILENAME); 

            $selectedLang = $_GET["lang"];
                if(!isset($selectedLang)){
                    $selectedLang = "de";
                }
            $langURL = "?lang=" . $selectedLang;

            $conn = new mysqli($dbServer, $dbUser, $dbPass, $dbName);
            $conn->set_charset("utf8");
            if($conn->connect_error){
                die("Connection failed: " . $conn->connect_error);
            } 
            // fetch main translations
            $location = "%main%";
            $stmt = $conn->prepare("SELECT tID, " . $selectedLang . " FROM TranslationsMain WHERE location LIKE ? ORDER BY tID");
            $stmt->bind_param("s", $location);
            $stmt->execute();
            $result = $stmt->get_result();  
            while($arrTranslations = $result->fetch_assoc()){
                $trans[] = array("ID" => $arrTranslations["tID"], "trans" => $arrTranslations[$selectedLang]);
            }
            $conn->close();

            // get main translations by ID
            function fetchTransMain($trans, $itemID){
                foreach($trans as $key => $val){
                    if($val["ID"] == $itemID){
                        return $val["trans"];
                    }
                }
            }
        ?>

        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta name="author" content="Some author" />
        <meta name="description" content="Created: 2015-06" />

        <base href="http://www.myurl.de" target="_self" />

        <title>Some title</title>

        <!-- CSS -->        
        <link rel="stylesheet" type="text/css" href="includes/styles.css" />
        <!-- CSS - Font Awesome -->
        <link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" />

        <!-- include favicon -->
        <link rel="shortcut icon" href="images/favicon/favicon.ico" type="image/x-icon" />
        <link rel="icon" href="images/favicon/favicon.png" type="image/png" />
        <link rel="icon" sizes="32x32" href="images/favicon/favicon-32.png" type="image/png" />
        <link rel="icon" sizes="64x64" href="images/favicon/favicon-64.png" type="image/png" />
        <link rel="icon" sizes="96x96" href="images/favicon/favicon-96.png" type="image/png" />
        <link rel="icon" sizes="196x196" href="images/favicon/favicon-196.png" type="image/png" />
        <link rel="apple-touch-icon" sizes="152x152" href="images/favicon/apple-touch-icon.png" />
        <link rel="apple-touch-icon" sizes="60x60" href="images/favicon/apple-touch-icon-60x60.png" />
        <link rel="apple-touch-icon" sizes="76x76" href="images/favicon/apple-touch-icon-76x76.png" />
        <link rel="apple-touch-icon" sizes="114x114" href="images/favicon/apple-touch-icon-114x114.png" />
        <link rel="apple-touch-icon" sizes="120x120" href="images/favicon/apple-touch-icon-120x120.png" />
        <link rel="apple-touch-icon" sizes="144x144" href="images/favicon/apple-touch-icon-144x144.png" />
        <meta name="msapplication-TileImage" content="favicon-144.png" />
        <meta name="msapplication-TileColor" content="#ffffff" />

        <script>
            var baseURL = '<?php echo $baseURL; ?>';
            var pageURL = '<?php echo $pageURL; ?>';
            var pageName = '<?php echo $pageName; ?>';
            var selectedLang = '<?php echo $selectedLang; ?>';
        </script>
    </head>   
    <body>

Now this is not working and I think I am probably missing a couple of things but I couldn't find a good tutorial or guideline on that. Also, I am not sure if there is anything else I need to do in order to start and set up the session.

Can someone help me with this ?

Note:
This is only about checking if a user is already logged in since all the actual user registration and verification is done on the separate login page and for this I already have the code working.

Update: Enabling error messages returns the following errors:

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /homepages/21/d580042014/htdocs/index.php:2) in /homepages/21/d580042014/htdocs/includes/header.php on line 9

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /homepages/21/d580042014/htdocs/index.php:2) in /homepages/21/d580042014/htdocs/includes/header.php on line 9
array(0) { } 
Warning: Cannot modify header information - headers already sent by (output started at /homepages/21/d580042014/htdocs/index.php:2) in /homepages/21/d580042014/htdocs/includes/header.php on line 12

Notice: Undefined index: lang in /homepages/21/d580042014/htdocs/includes/header.php on line 18

Update:
As per the comments I now posted everything that's currently in the header.

Many thanks in advance.

like image 532
TaneMahuta Avatar asked Jun 24 '15 15:06

TaneMahuta


People also ask

How can I check if a user is logged in PHP?

session_start(); Check if $_SESSION["loggedIn" ] (is not) true - If not, redirect them to the login page.

How do I redirect a user to login?

You can use session variable to do this, you ust be set session on login. So on edit page starting you can write following code to check wheter user is logged in or not.. your condition is bad, a simple issset($_SESSION) is not enough. another session might be set somewhere else.

How can check user already login in asp net?

You need to set FormsAuthentication. SetAuthCookie(PrimaryKey, false); when user is loggedIn. Here, PrimaryKey is the key that you can use throughout the session for identification of the user using User.Identity.Name . Also, when user log out of the application, you will call FormsAuthentication.


2 Answers

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.
like image 67
Funk Forty Niner Avatar answered Nov 03 '22 01:11

Funk Forty Niner


You need to move

session_start();
if((!isset($_SESSION['login']) && $_SESSION['login'] != '')){
    header ("Location: login.php");
}

to the top of the scrip and move ! inside the bracket.

like image 42
petebolduc Avatar answered Nov 02 '22 23:11

petebolduc