I cannot submit a form in php and redirect

1.4k Views Asked by At

I have a page (index.php) is a login page so I need to validate a user and redirect to other page but header(Location:"welcome.php"); is not working, the sql query is ok but I only get the message "Login Successful" and the page doest redirect to the other called welcome.php I'm newbie in PHP so any help is great!

<!DOCTYPE html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="favicon.ico">

<title>Login</title>
<link href="bootstrap.min.css" rel="stylesheet">
<link href="signin.css" rel="stylesheet">
</head>

<body>

<div class="container">

  <form class="form-signin" role="form" action="<?=$_SERVER['PHP_SELF']?>" method="POST">
    <h2 class="form-signin-heading"><center>Bienvenido!</center></h2>

<input type="text" name="username" class="form-control" placeholder="Username" required="" autofocus="">
<input type="password" name="password" class="form-control" placeholder="Password" required="">

  <div class="checkbox">
      <label><input type="checkbox" value="remember-me"> Remember me </label>
  </div>

<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
  </form>

</div>



<?php
    $link = mysqli_connect("localhost","root","root","testdb") or die     ("error".mysqli_error($link));

     $username = $_POST['username'];
     $password= $_POST['password'];

     if (isset($_POST['username'])) {
       $sql = "SELECT * FROM testdb.user WHERE username='$username' and password='$password'";
       $result = mysqli_query($link,$sql);
         if ($result);
            {
              $num=mysqli_num_rows($resultado);
            }     

         if($num==1)
           {
            header("Location: welcome.php");
            exit();
           }else{

            header("Location:wrong.php");
           }
           mysqli_free_result($result);
           mysqli_close();
      }
?> 
2

There are 2 best solutions below

6
Jimmyt1988 On BEST ANSWER

thought this might help on top of the real answer that robbmj provided

  1. Create 3 folders...

    • Views
    • Models
    • Controllers
  2. In the Views folder, create a php file called "Login.php"

  3. Inside that php page paste your html form:

    <!DOCTYPE html>
        <head>
        </head>
    
        <body>
    
            <div class="container">
    
                <form class="form-signin" role="form" action="<?=$_SERVER['PHP_SELF']?>/Controllers/Login.php" method="POST">
                    <h2 class="form-signin-heading"><center>Bienvenido!</center></h2>
    
                    <input type="text" name="username" class="form-control" placeholder="Username" required="" autofocus="">
                    <input type="password" name="password" class="form-control" placeholder="Password" required="">
    
                    <div class="checkbox">
                        <label><input type="checkbox" value="remember-me"> Remember me </label>
                    </div>
    
                    <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
                </form>    
            </div>
        </body>
    </html>
    
  4. Inside your Models folder, create a file called SQLDbContext.php

  5. Inside that file place the code like so:

    class SQLDbContext
    {
        public $link;
    
        public function Connect()
        {
            $this->link = mysqli_connect( "localhost", "root", "root", "testdb") 
            or die ( "error" . mysqli_error( $enlace ) );
        }
    
        public function __Destruct()
        {
            mysql_free_result($result);
            mysql_close();
        }
    }
    
  6. Inside your Models folder, create a file called AuthenticationRepository.php

  7. Inside that file, place the code like so:

    require_once( "SqlDbContext.php" );
    
    class AuthenticationRepository extends SQLDbContext
    {          
        public function __Construct()
        {
            $this->Connect();
        }
    
        public function GetUsersByUsernameAndPassword( $username, $password )
        {
            $sql = "SELECT * FROM testdb.user WHERE username='$username' and password='$password'";
            $result = mysqli_query( $this->link, $sql );
            return $result;    
        }             
    }
    
  8. Create a Login.php file inside Controllers (You'll notice I changed your action to /Controllers/Login.php in your Login view

  9. Inside that php file, place your logic to login:

    require_once( "../Models/AuthenticationRepository.php" );
    
    $authenticationRepository = new AuthenticationRepository();
    $username = $_POST[ "username" ];
    $password = $_POST[ "password" ];
    
    $usersInDb = $authenticationRepository->GetUsersByUsernameAndPassword( $username, $password );
    $num = mysqli_num_rows( $usersInDb );
    
    if( $num == 1 )
    {
        header("Location: Views/Welcome.php");
    }
    else
    {
        // Set a $_SESSION here and in the Views/Login.php check for that $_SESSION being set
        header("Location: Views/Login.php");
    }
    

NOTES:
- You will notice that nothing has been echo'd to the screen before a header(...) has been issued.
- You will notice that all logic has been divided up (wrongly but itll get you started).
- YOU STILL NEED TO DO SQL injection checks and validation etc, but i'll leave that for you to do buddy

By doing all of this, you avoid alot of the problems you have at the moment... There is so much you can do here to improve this code, In fact, the above code really isn't too hot either, but it's a step in the right direction... Seperate all of your stuff out... Check out http://www.laravel.com which is an MVC framework made to help you not screw things up too much :)

enter image description here

6
robbmj On

It is because you are sending output before issuing the redirect. You can't change the HTTP headers once you have started printing the body of the HTTP message.

// echo "Login Successful"; // remove this line and all other HTML
header("Location: welcome.php");
exit();

Basically you have to restructure the program so that when the form is submitted you are not sending output to the browser.

Example pseudo code:

if user has submitted the form then
    authenticate user
    if authentication is successful then
        redirect user to welcome.php
    else
        show login page and error message
else
    show login page