-1

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();
      }
?> 
jhuamanchumo
  • 385
  • 2
  • 7
  • 21
  • The robbmj answer is quite possibly the issue. However, can I suggest your page redirects to a separate processing php page explicitly with the task of logging in... and then from the result of that php (which does not need to output anything), you can redirect to the dashboard or whatever you're going to... In this case you'll have views/Login.php, Controllers/LoginController.php, Views/Dashboard.php... – Jimmyt1988 Jul 27 '14 at 00:58
  • 1
    Your code is vulnerable to SQL injections. You should read on [how to prevent them in PHP](http://stackoverflow.com/q/60174/53114). – Gumbo Jul 27 '14 at 01:05
  • You **do not** send HTTP response headers **after** the response body has already been sent to the client. – Ryan Jul 27 '14 at 01:09
  • I put the PHP code at the begin of the page but when I submit the form with correct values I got a blank page(index.php) – jhuamanchumo Jul 27 '14 at 01:12
  • Firstly, you're mixing MySQL APIs `mysqli_` and `mysql_` and they do **not** mix. Plus, make sure that short open tags are ON, otherwise change `=$_SERVER['PHP_SELF']?>` to `` - Plus, you're also calling the wrong variable with `$num=mysqli_num_rows($resultado);` - `$resultado` is a stray variable. This `echo "Login Successful);` is invalid also. There are way too many errors in your code for me to give you an actual "answer". Include error reporting in your code. `error_reporting(E_ALL); ini_set('display_errors', 1);` – Funk Forty Niner Jul 27 '14 at 01:14
  • Plus, another I spotted `if ($result);` that's invalid, and another stray variable `$enlace` – Funk Forty Niner Jul 27 '14 at 01:19

2 Answers2

2

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
robbmj
  • 16,085
  • 8
  • 38
  • 63
  • 1
    This won't work as he has HTML outputted beforehand. He needs to move the PHP part before the HTML first, then comment out the echo. – Aziz Saleh Jul 27 '14 at 00:55
  • I put the PHP code at the begin of the page but when I submit the form with correct values I got a blank page called index.php – jhuamanchumo Jul 27 '14 at 01:00
  • Even with your edit, your answer will fail. Who upvoted this? – Funk Forty Niner Jul 27 '14 at 01:14
  • I've removed my downvote. However, do look through some of my comments left under OP's question; there are far too many things wrong with it, which is why I did not submit an "answer". This is just a "can of worms" I don't want to open and blow up in my face. – Funk Forty Niner Jul 27 '14 at 01:22
  • @Fred-ii- My original intention of restructuring the OP's code was to help him to understand the pseudo code. However when I read the PHP more thoroughly I saw the amazing number of errors, bad practices and vulnerability in it. At that point I decided to remove it from the answer. – robbmj Jul 27 '14 at 01:25
  • Which is why I removed my downvote, since you have outlined one of the errors as per [**OP's original post**](https://stackoverflow.com/revisions/24976884/1); outputting before header. But now, the OP has changed the question/code without showing as an edit. I have voted to close the question. – Funk Forty Niner Jul 27 '14 at 01:33
1

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

Jimmyt1988
  • 20,466
  • 41
  • 133
  • 233
  • This will also fail. Please go over some of my comments left under OP's question. You're still making many of OP's same mistakes and syntax errors. – Funk Forty Niner Jul 27 '14 at 01:29
  • Forgot to take out his echo... This should help him out immensly.. even though it's not correct mvc. – Jimmyt1988 Jul 27 '14 at 01:34
  • OP's code is an absolute mess. Mixing MySQL APIs for instance, and so does your answer. This `echo "Login Successful);` should be `echo "Login Successful";`, plus the `mysql_` functions `mysql_free_result` and `mysql_close()`. This is only part of the errors. I will not downvote, but if you do (from someone else), you will know why. Just trying to help you out here ;-) – Funk Forty Niner Jul 27 '14 at 01:36
  • Fred... :), I've been coding for 8 years of my life in C++, C#, PHP, JavaScript, Java... I've made computer games, desktop applications, websites using webforms, mvc, windows phone applications, android applications... You don't need to worry about my code :) The above is a great way to get him to think about how to order stuff to help him out... he doesn't need to know the specific mistakes, he will learn these in time! the idea is to bring clarification so he can see his code flaws on his own... Thanks for your time though!!!... :) – Jimmyt1988 Jul 27 '14 at 02:09
  • You've a point there Jimmy & you're quite welcome. Many a time people will post answers while still including OP's mistakes such as mixing MySQL APIs for instance. This stands at getting downvotes (sidenote); I was merely pointing these out in case you'd get any or that it would keep giving the OP problems that he/she may not be aware of, or how to solve them. I like to help out with answers & the questions themselves using comments; sometimes they take them, sometimes not. I'm sure you're a good coder, I'm not questioning that fact. I believe you've led the OP in the right direction, *cheers* – Funk Forty Niner Jul 27 '14 at 03:18
  • I've +1 by the way. ;-) – Funk Forty Niner Jul 27 '14 at 03:19