laurad
laurad

Reputation: 91

redirect using header in php

I don't understand the problem in my code.I am trying to redirect the user if username and password are correct.

I read from a documentation that "header must be called before any actual output is sent". What kind of output is this referring to? I don't think I'm outputting anything. Here is my code. Thanks in advance.

<?php
require "index-header.html";
?>

<div class="display">
    <?php 
    if(isset($_POST["logout"])) {
        session_unset();
        session_destroy();
    }

    if(isset($_POST["login"])) {
        $name = $_POST["name"];
        $password = $_POST["password"];

        // connect to database
        $db = connect();

        $query = "SELECT admin_name, admin_password FROM login WHERE admin_name = :name AND admin_password = :password";
        $login = $db->prepare($query);
        $login->execute(array(
            ":name" => $name,
            ":password" => $password
        ));

        if($login->rowCount()) {
            // start session
            $_SESSION["admin"] = "Laura";
            header("Location:admin.php");
            exit;
        }
        else {
            echo "<p class='message'>Incorrect username or password</p><br>";
            require "login-form.html";
        }
    }
    else {
        require "login-form.html";
    }
    ?>
</div>

Upvotes: 1

Views: 77

Answers (3)

rick6
rick6

Reputation: 467

Output means any HTML/CSS/JavaScript (or other data) being output in the browser.

There's two problems in your code that would prevent your header change from redirecting:

require "index-header.html";

and

<div class="display">

The better explanation for this in basic terms is that headers can only be modified before any output begins. Every time you visit a web page, headers are sent before the body. Headers can give information like character sets, response codes (like 404), or redirect information. What if you needed to display Arabic characters instead of English? The headers would need to let the browser know how to handle the incoming body (or how you're referring to it: output).

Upvotes: 3

Scream
Scream

Reputation: 100

As mentioned by rick6, before redirect you can not use HTML. You can move your login check before require

<?php
/* check login */
// if admin redirect
// else
// $message = "<p class='message'>Incorrect username or password</p><br>";

require "index-header.html";
echo '<div class="display">';
....
?>

Upvotes: 2

Thomas Rbt
Thomas Rbt

Reputation: 1538

header must be called before any actual output is sent.

But, here, <div> is an input, and you require index-header.html, so header location can't works.

You can use JS :

    function nextpage() {
        document.location.href='nextpage.php';
    }
    nextpage();

Upvotes: 1

Related Questions