-3

I have some PHP files with session_start() function and some settings to cookie parameters. They are pure PHP pages and there is no HTML at all. Now I want to add some background color and some forms and tables in those PHP pages. When I add any bit of HTML it gives me that error of "headers already passed"!

I want to know the correct way of embedding PHP and HTML! please let me know.

Here is the code:

<?php
include 'functions.php';
secure_session_start();

define("HOST", "localhost"); // The host you want to connect to.
define("USER", "admin"); // The database username.
define("PASSWORD", "password"); // The database password. 
define("DATABASE", "test"); // The database name.
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);

if(isset($_POST['name'], $_POST['password'])) { 
        $name = $_POST['name'];
        $password = $_POST['password']; // The hashed password.
        if(login($name, $password, $mysqli) == true) {
            // Login success
            echo 'Success: You have been logged in!';
    }    else {
         // Login failed
         echo 'Wrong ID/password!';
    }
} else { 
   // The correct POST variables were not sent to this page.
   echo 'Invalid Request';
}
?>

3 Answers3

1

Do everything before you output HTML, it's that simple.

<?php

    session_start();

    /* here be dragons, i.e. more PHP code */

?>
<!DOCTYPE html>

<html>
...
</html>
deceze
  • 510,633
  • 85
  • 743
  • 889
0

In PHP you can't have any HTML before you have a header. Headers must be before everything.

bzupnick
  • 2,646
  • 4
  • 25
  • 34
0

I agree with @deceze, simply because forcing yourself to process data before rendering output ensures a better separation of concerns (you're less likely to have SQL intermixed with HTML, which frankly can drive a person to insanity)

However; for the sake of completeness, here's a "workaround" to ensure that no output is dumped before you want it.

ob_start() and ob_get_clean()

ob_start() begins output buffering, and ob_get_clean() returns (and ends) output buffering. Used in conjunction you can ensure that output won't be sent.

<?php 
    // start output buffering
    ob_start();
?>

<p>Write HTML, start sessions, eat pie</p>
<?php session_start(); ?>

<?php
    // dump all the things that output
    // buffering captured
    echo ob_get_clean();
?>

The output can be captured into a variable and post-processed if you need. I will add a disclaimer though: this is not an excuse to just mash HTML and SQL and any other technology into a stew, and bolt it onto the internet.

Dan Lugg
  • 20,192
  • 19
  • 110
  • 174