Alex Rivera | Logout

Outputting HTML with echo considered bad practice in PHP?

Asked 2011-11-29T21:33:08.483
8

In PHP, I'm using an if statement to identify whether a user is logged in or not, and depending on the result, displaying the main menu (if logged in) or a "you need to login" message if not. I am doing this like so:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <link rel="stylesheet" href="style.css" type="text/css" />
    <title>Home</title>
</head>
<body>
    <div id="header">
       <a href="index.php"><img src="wtcdblogo.png" alt="WTC DB logo" /></a>
    </div>
    <?php 
       if($_SESSION['loggedIn'] == 1) {
          echo "<div id='main'>MAIN MENU stuff goes here</div>";
       } else {
          echo "<div id='main'>Please login...</div>";
       } 
    ?>
</body>
</html>

As you can see, the code to display either the main menu or the "please login" message is produced by an echo. Is this bad practice, perhaps there's a better way?

By the way, I've cut out most of the HTML from the echos in my snippet above. The main menu is made up of a list, but I didn't bother including that as it's irrelevant to the question, I guess.

Edit
Report

1 Answer

7

There's nothing wrong with echo for html, when used in moderation. Just don't use it for long multi-line blocks. You'll invariably end up with some ugly construct requiring escaping and whatnot, which makes things even uglier to read.

If the html you're outputting is "static" (no variables to insert), then consider breaking OUT of php mode (?>) and simply dumping the html as is. If you do need to insert variables, then consider using a HEREDOC, which act like a double-quoted string, but without the quotes.

answered 2011-11-29T21:38:20.083

Your Answer