Outputting HTML with echo considered bad practice in PHP?

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.

Answers


I consider it to be bad practice. Not sure about what anyone else thinks. For one thing, it looks terrible in text editors with syntax highlighting, then you have to worry about escaped strings, etc.

This is how I do it:

   <div>
      <? if ($_SESSION['loggedIn'] === 1): ?>
         <div id="main">Main Menu stuff goes here</div>
      <? else: ?>
         <div id="main">Please log in...</div>
      <? endif ?>
   </div>

You can hop out of the PHP tags and use straight up HTML. There are pros and cons to doing it this way. I like it way better than echoing stuff out. Other options would be to render new views into those areas based on the results of the if statements. Lots of possibilities, but the above is just one way to make that a little cleaner and (I think) better.


Need Your Help

How can retrieve string formData js in c#

javascript c# asp.net-web-api form-data

I have to retrieve the value of "idPerson" in my web api in .net.

How to store JSON data from two sources in javascript objects when the data is pulled in at different rates?

javascript jquery reddit embedly

I am trying to create Article objects from links pulled in with ajax (using the jquery reddit api) combined with extra information about the links (pulled in from the embed.ly jquery api).