-2

Having a file that only auth people can see. And trying to redirect other users before page loads. Following method permits page to load which i do not want.

<?php 
session_start();
// Check if person is logged in
if($_SESSION['login'] != 'true'){ //if login in session is not set

 echo "<script>
window.location = 'index.php';
</script>";
}

?>

Edit Working Version.

<?php 
session_start();
// Check if person is logged in
if($_SESSION['login'] != 'true'){ //if login in session is not set


header('Location: index.php');
exit;
}

?> 

P.S. Thanks.

Igor
  • 11
  • 3

4 Answers4

2

Try something like this instead :

<?php 
session_start();
// Check if person is logged in
if($_SESSION['login'] != 'true'){ //if login in session is not set
header("Location: index.php");
die();
}
SpencerX
  • 5,453
  • 1
  • 14
  • 21
  • 1
    [Put `exit` after the header call to be safe.](http://stackoverflow.com/questions/3553698/php-should-i-call-exit-after-calling-location-header) – scrowler Jul 27 '14 at 23:31
2

Since you're using PHP, you may want to take a look at the header documentation. More specifically, setting the Location on the header will trigger a 302 Redirect to the page you want it to go to. For example:

<?php
    if($_SESSION['login'] != 'true') {
        header('Location: index.php');
        exit;
    }
?>

This will tell the page to set the location of the page to index.php. It is important to note, however, that you can only do this before any markup is sent to the DOM (such as the <html> tag, or any other content for that matter), or else the redirect will fail.

You also will want to add exit; after the header change to ensure that any other logic in the PHP file will not execute.

Mike Koch
  • 1,540
  • 2
  • 17
  • 23
0

This works for me.

session_start();

    // Check if person is logged in
if (!$_SESSION['login'])
{
    // Redirect to Login Page
    header( 'location: login.php' );
    exit;
}
doschni
  • 43
  • 8
  • Here you're only checking for a loose boolean true, which could be bool true, `1`, `"yes"`, `"no"`, **`"false"`** etc. Since OP is literally writing out "true" or "false", you need to check for that exact occurrence. – scrowler Jul 27 '14 at 23:37
0

Send a location header via PHP. http://php.net/manual/de/function.header.php

<?php
header("Location: http://www.example.com/"); /* Browser umleiten */

/* Stellen Sie sicher, dass der nachfolgende Code nicht ausgefuehrt wird, wenn
   eine Umleitung stattfindet. */
exit;
?>

Programming a foolproof loginsystem is quite hard to achieve. I suggest u use a well tested library instead of reinventing the wheel. However that's outside the scope of this question.

wedi
  • 1,332
  • 1
  • 13
  • 28
  • 3
    Nothing is ever foolproof in web security, there's nothing wrong with reinventing a 99% effective solution that takes you 20 minutes to write up when implementing a third party library will weigh down your system – scrowler Jul 27 '14 at 23:35