0

I am creating a very simple website with user accounts. In my 'login.php', the login details are sent via a form to the page 'home.php' where the username/password are checked with a database and then:

If they are correct, the HTML in my page home.php is displayed. If they are not correct, the HTML is not displayed and I use the 'header' function to go back to the login.php page.

Here is my code :

<?php
    if ($identification==1) { // IF THE IDENTIFICATION IS CORRECT
?>
// Here all the HTML of my page is displayed
<?php   
    }else{ 
        header ('location : login.php'); 
    }
?>

When I do it this way, the redirection is not made and I just have a blank page, but when I change it to:

<?php
    if ($identification==1) { 
?>
<!-- Here all the HTML of my page is displayed -->
<?php   
    }else{ 
?>
echo "<script type='text/javascript'>document.location.replace('login.php');</script>";
<?php
    }
?>

It works perfectly! Do you have an idea why it is not working with header?

Also, is it secured to do the check of username/password directly in the home page, or should I do it in a 'test.php' page which would redirect to the 'home.php' page if the credentials are correct ?

EDIT, works like this

  if ($identification!=1) { header ('Location: home.php'); exit;
  };
  • 2
    `Location` and remember to add an exit after the header line. – Jonnix Aug 23 '17 at 08:38
  • 1
    In the very top of your script, just have: `if ($identification != 1) { header('Location: login.php'); exit; }`. Then you don't need to wrap the whole site in an `else`-block. Just make sure that there is _no_ output before your `header()`-call, not even a space/blank line or it won't work. – M. Eriksson Aug 23 '17 at 08:44
  • Thanks for the tip, much better! I edited my question, doesnt seem to be working :( – Olivia Delpierre Aug 23 '17 at 09:04

2 Answers2

1

I checked and tried to find out the problem! The results are the way you added the redirection is wrong:

Use this instead! colon : should be appended to location!

<?php
    if ($identification==1) { // IF THE IDENTIFICATION IS CORRECT
?>
// Here all the HTML of my page is displayed
<?php   
    }else{ 
        header('Location: login.php'); 
    }
?>

I hope this helped!

Mr Pro Pop
  • 666
  • 5
  • 19
0

You don't have to check username password on homepage, instead you should check it either in login.php or may be an action file of login.php. If the username and passwords are correct you can set a session value and can redirect the user to home.php based on the session value, else you can redirect the user to login.php

Now for the use of header you can simply use

if( // check your condition here...) {
    header("location:home.php");
    exit();
}else{
    header("location:login.php");
    exit();
}
jyotisankar
  • 134
  • 1
  • 4