title: force login page before index
body: <p>I have a login form that displays a message when a user either registers or logins in. I would like the login page to open first and after successful login then index.php can be shown. also should someone try and access  /index.php directly it must still direct them to login.php to be authenticated. I have tried some examples of other peoples codes but i cannot get the page to authenticate the user.</p>
  
  <p>My Login.php code:</p>
  
  <pre><code>&lt;?php
  session_start();
  require_once('connect.php');
  if(isset($_POST) &amp; !empty($_POST)){
  $username = mysqli_real_escape_string($connection, $_POST['username']);
  $password = md5($_POST['password']);
  
  $sql = "SELECT * FROM `login` WHERE username='$username' AND password='$password'";
  $result = mysqli_query($connection, $sql);
  $count = mysqli_num_rows($result);
  if($count == 1){
      $_SESSION['username'] = $username;
  }else{
      $fmsg = "Invalid Username/Password";
  }
  }
  if(isset($_SESSION['username'])){
  $smsg = "User already logged in";
  }
  
  
  ?&gt;
  &lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;title&gt;User Login in PHP &amp; MySQL&lt;/title&gt;
  &lt;!-- Latest compiled and minified CSS --&gt;
  &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" &gt;
  
  &lt;!-- Latest compiled and minified JavaScript --&gt;
  &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" &gt;&lt;/script&gt;
  
  &lt;link rel="stylesheet" type="text/css" href="styles.css"&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;div class="container"&gt;
    &lt;?php if(isset($smsg)){ ?&gt;&lt;div class="alert alert-success" role="alert"&gt; &lt;?php echo $smsg; ?&gt; &lt;/div&gt;&lt;?php } ?&gt;
    &lt;?php if(isset($fmsg)){ ?&gt;&lt;div class="alert alert-danger" role="alert"&gt; &lt;?php echo $fmsg; ?&gt; &lt;/div&gt;&lt;?php } ?&gt;
    &lt;form class="form-signin" method="POST"&gt;
      &lt;h2 class="form-signin-heading"&gt;Please Register&lt;/h2&gt;
      &lt;div class="input-group"&gt;
        &lt;input type="text" name="username" class="form-control" placeholder="Username" required&gt;
      &lt;/div&gt;
      &lt;label for="inputPassword" class="sr-only"&gt;Password&lt;/label&gt;
      &lt;input type="password" name="password" id="inputPassword" class="form-control" placeholde r="Password" required&gt;
      &lt;button class="btn btn-lg btn-primary btn-block" type="submit"&gt;Login&lt;/button&gt;
      &lt;a class="btn btn-lg btn-primary btn-block" href="register.php"&gt;Register&lt;/a&gt;
    &lt;/form&gt;
  &lt;/div&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>