-3

I've been trying to redirect the user to the Userpanel.php page after a successful login, but header() method doesnt work in the if condition. Here is the code:

    <?php

    $db_host="localhost";
    $db_name="researchblog";
    $db_user="root";
    $db_pass="";
    $conn=mysqli_connect($db_host, $db_user, $db_pass);
    mysqli_select_db($conn,$db_name);

    if(isset($_POST['username']))
    {
        $uname=$_POST['username'];
        $password=$_POST['password'];

        $sql="select * from users where username='".$uname."' AND password ='".$password."'";

        $result=mysqli_query($conn,$sql);
        if(mysqli_num_rows($result)==1)
        {
            header("location:Userpanel.php");

        }
        else
        {
            echo "<script> alert('Failed to Login') </script>";

        }
    }

?>
Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34

2 Answers2

1

Try this may be it works in your case.

if(mysqli_num_rows($result)==1)
            {
              echo "<script>window.location = 'Userpanel.php';</script>";
            }
            else
            {
                echo "<script> alert('Failed to Login') </script>";   
            }
Waqas Ahmad
  • 426
  • 1
  • 3
  • 16
0

Remove all white space before the <?php tag, and after the ?> tag (or at least remove the ?> to automatically cause php to eliminate blank space into the html file and improper injection into the header.

See these answers for a more elaborate explanation.

PHP Header redirect not working (https://stackoverflow.com/a/24928578/1691103)

Which has a link to the following useful question answer.

How to fix "Headers already sent" error in PHP (https://stackoverflow.com/a/8028987/1691103)

Also try making sure that header name first character is uppercase, in your case header('location: Userpanel.php') should be header('Location: Userpanel.php')

Vahe
  • 1,699
  • 3
  • 25
  • 76
  • Whitespace *after* the `header()` shouldn't cause a problem. – Barmar Apr 10 '19 at 16:28
  • I don't know if it is by mistake but the header of the script has white space. Please check against the actual source. – Vahe Apr 10 '19 at 16:32
  • 1
    @Vahe well i did remove all the white spaces , but still :/ –  Apr 10 '19 at 16:37
  • As a final resort, try to enable errors temporarily by inserting `error_reporting(E_ALL);` above your first line of code under ` – Vahe Apr 10 '19 at 16:46
  • @Moon sounds like then you are not outputting content before header so make sure that the last suggestion in the answer on uppercase of `location` is applied. – Vahe Apr 10 '19 at 17:16