PHP: how to check if a user has already been registered and otherwise redirected to the login page

I am new to PHP and struggling with the following:

I have a page where I want to check if someone is a registered user before allowing them to see the contents of the site. Therefore, I thought that in my header file (which is indicated on all individual pages via require_once("includes/header.php"); ) I can check this and redirect them to the login page ( login.php ) if they have not already entered into the system.

So, here is all 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 does not work, and I think that I probably missed a couple of things, but I could not find a good tutorial or guide on this. Also, I'm not sure if there is anything else I need to do to start and set up a session.

Can someone help me?

Note:
This only applies to verifying that the user is already registered, since all the actual registration and verification of the user is performed on a separate login page, and for this I already have a code.

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:
In accordance with the comments, I have now posted everything that is currently in the header.

Thank you very much in advance.

+5
source share
4 answers

Update: issue resolved in chat .


According to your editing, change this block:

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

in

 <?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 to start a session in all of your files using sessions.
  • Make sure your file does not have a Byte Order Sign (BOM).
  • There are no spaces before <?php , etc., this has already been set in the comments.

Use a code editor such as Notepad ++ https://notepad-plus-plus.org/ and save it as UTF-8 without a specification that guarantees no byte order sign.

Also using the new session array validation method.

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

Also make sure that none of your included / required files have the same problems, including login.php .


Footnote:

In the Inside Notepad ++ drop-down menu you will see

  • Encoding. It will show you what the real encoding of the file is for.

If it shows a byte order mark, do the following:

  • Click "Encoding."
  • Convert to UTF-8 without specification
  • Save the file.

    • Do this for all of your files.

Link (s):


Sidenote:

You must change $stmt->execute(); on the

 if(!$stmt->execute()){ trigger_error("there was an error....".$conn->error, E_USER_WARNING); } 
  • It is better to catch possible errors in your request.
+10
source

You need to move

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

at the top of the script and move ! inside brackets.

+2
source

Put the user profile in session variables in the PHP script that you call after the login page

 $_SESSION['user_id'] = $row["user_id"]; $_SESSION['profile_id'] = $row["profile_id"]; $_SESSION['name'] = $row["name"]; $_SESSION['surname'] = $row["surname"]; $_SESSION['application_auth'] = $row["application_auth"]; 

Put the following code at the top of each page that you want to protect invalid users.

 <?php include("sessionCheck.php"); ?> 

Session verification script In this case, I also check whether the user has the right to view a specific page using profile_id, but you can delete it.

 <?php session_start(); if(!IsSet($_SESSION['user_id']) or $_SESSION['profile_id'] !=1) { header("location: http://www.yourdomain.com/login.php?message=Invalid user"); } ?> 
+1
source

The next part should go before include "system/config.php"; , because it seems that this file is output, as well as the fact that the following code is independent of any other data.

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

The second:

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

Probably should be: if(!isset($_SESSION['login']) && $_SESSION['login'] == ''){

Value == '' , not != ''

The user who is not logged in most likely (depending on your code) does not matter, so your code will check to see if it is empty, so only registered users will be redirected.

Hence:

 <?php define("someUnguessableValue", "anotherUnguessableValue"); session_start(); if(!isset($_SESSION['login']) && $_SESSION['login'] == ''){ header("location:login.php"); } include "system/config.php"; //.... the rest ?> <!DOCTYPE html> <html> <head> 

If it is not redirected, then $ _SESSION ['login'] is most likely to be installed, you need to clear the cookies for this domain.

+1
source

All Articles