Search code examples
phpsetcookie

PHP - setcookie(); not working ( Cannot modify header information - headers already sent )


I am getting this error:

Warning: Cannot modify header information - headers already sent by (output started at /removed/loginform.php:2) in /removed/loginform.php on line 24

I understand that I am getting the error when I try to set a cookie, and it's because setcookie can't have any output before it... the problem is, there is no output before it (At least from what I can see). It is saying that "< ?php" is a header, and I don't understand that. If setcookie can only be used in PHP and < ?php is a header, how is it even possible to use setcookie without getting this header error?

My code:

<!--Database Connections-->
<?php include "../../includes/dbpractice_con.php"; ?>

<?php 

//Declare variables
$username = "";
$password = "";
$message = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") { //Retrieve from form when submit is clicked.

    //Escape to prevent SQL injection.
    $username = mysqli_real_escape_string($connection, $_POST['username']);
    $password = mysqli_real_escape_string($connection, $_POST['password']);

    $check = mysqli_query($connection, "SELECT * FROM users WHERE username='$username' AND password='$password'");
    $rowCount = mysqli_num_rows($check);

    if ($rowCount == 1) {

        $cookieExpiration = time() + 757368000; //1 year

        setcookie("username", $username, $cookieExpiration);

    } else {
        $message = "Invalid username or password. <br/>Don't have an account? Click <a href=\"registerform.php\">here</a> to register.<br/><br/>";
    }

}


?>

<html>

Solution

  • <!--Database Connections--> is HTML output, even if it is just a comment. Remove that and try again.

    EDIT: There is also a space between the PHP blocks. Try putting the include in the main PHP block.