php – Error en la cabecera – Warning: Cannot modify header information – headers already sent

Question:

Este es el error:

Warning: Cannot modify header information – headers already sent by (output started at C:\xampp\htdocs\newop\template\header.php:80) in C:\xampp\htdocs\newop\mainindex.php on line 16

La línea 80 del header es esta (es una sola línea, solo que descompactada):

<div class="col-md-2 col-xs-2 device-select">
    <a href="budget.php?device=2">
        <img class="full-width" src="res/images/device2.jpg">
        </img>
    </a>
    <center class="popular-devices">
<?php echo $lang['header_dropdown_string_2'];?>
    </center>
</div>

… and this is the code:

<?php
session_start();
if (!isset($_SESSION['user'])){ header("Location: index.php"); }
?>
<html>
  <body>
<?php
  include("template/head.php");
  include("template/header.php");
  include ("db_files/db.php");
  $usermail = mysqli_real_escape_string($db, $_SESSION['user']);
  $strSQL = "SELECT nivel FROM usuarios where email ='$usermail'";
  $query = mysqli_query($db, $strSQL);
  while ($result = mysqli_fetch_array($query)){
    if ($result['nivel'] == 1 || $result['nivel'] == 2){
    header("location: userlist:php");
  }
  
}
  $state = array(
    1 => $lang['state_name_string_1'],
    2 => $lang['state_name_string_2'],
    3 => $lang['state_name_string_3'],
    4 => $lang['state_name_string_4'],
  );
?>
  <div class="content container">
    <div class="row no-margin no-padding">
      <div class="col-md-2 hidden-sm hidden-xs">
        <div class="mainuserimage">
          <img class="full-width" src="res/images/users/user1.png"/>
        </div>
        <div>
<?php
            $strSQL = "SELECT nombre, email, telefono FROM usuarios where email ='$usermail'";
            $query = mysqli_query($db, $strSQL);
            while ($result = mysqli_fetch_array($query)){
              echo "<i class='glyphicon glyphicon-user'></i> ".$result['nombre']."<br>";
              echo "<i class='glyphicon glyphicon-envelope'></i> ".$result['email']."<br>";
              echo "<i class='glyphicon glyphicon-earphone'></i> ".$result['telefono']."<br>";
            }
?>
        </div>
      </div>
      <div class="col-md-10 col-xs-12">
      <h3 class="main-title"><?php echo $lang['mainindex_string_1']; ?></h3><br>
        <div class="row">
          <div class="col-md-2 col-xs-3">
            <p><?php echo $lang['mainindex_string_2']; ?></p>
          </div>
          <div class="col-md-2 col-xs-3">
            <p><?php echo $lang['mainindex_string_3']; ?></p>
          </div>
          <div class="col-md-2 col-xs-3">
            <p><?php echo $lang['mainindex_string_4']; ?></p>
          </div>
          <div class="col-md-2 hidden-sm hidden-xs">
            <p><?php echo $lang['mainindex_string_5']; ?></p>
          </div>
          <div class="col-md-2 col-xs-3">
            <p><?php echo $lang['mainindex_string_6']; ?></p>
          </div>
          <div class="col-md-2 hidden-sm hidden-xs">
            <p><?php echo $lang['mainindex_string_7']; ?></p>
          </div>
<?php
            $strSQL = "SELECT id, marca, modelo, imei, descripcion_problema, problem, problem2, problem2_namees, estado, fecha_creacion FROM tickets, problem2 WHERE tickets.email = '$usermail' AND tickets.problem2 = problem2.problem2_id";
            $query = mysqli_query($db, $strSQL);
            while($result = mysqli_fetch_array($query)){ ?>
              <div class="col-md-2 col-xs-3">
                <p><a href="repairdetail.php?id=<?php echo $result['id']; ?>"><i class="glyphicon glyphicon-list-alt"></i></a>  <?php echo $result['marca']; ?></p>
              </div>
              <div class="col-md-2 col-xs-3">
                <p><?php echo $result['modelo']; ?></p>
              </div>
              <div class="col-md-2 col-xs-3">
                <p><?php echo $result['imei']; ?></p>
              </div>
              <div class="col-md-2 hidden-sm hidden-xs">
                <p><?php echo $result['problem2_namees']; ?></p>
              </div>
              <div class="col-md-2 col-xs-3">
                <p><?php echo $state[$result['estado']]; ?></p>
              </div>
              <div class="col-md-2 hidden-sm hidden-xs">
                <p><?php echo $result['fecha_creacion']; ?></p>
              </div>
<?php
            }
?>
          </div>
        </div>
    </div>
  </div>
<?php
  include("template/footer.php");
?>
  </body>
</html>

Answer:

Move the block:

include ("db_files/db.php");
$usermail = mysqli_real_escape_string($db, $_SESSION['user']);
$strSQL = "SELECT nivel FROM usuarios where email ='$usermail'";
$query = mysqli_query($db, $strSQL);

while ($result = mysqli_fetch_array($query)){
    if ($result['nivel'] == 1 || $result['nivel'] == 2){
        header("location: userlist.php"); //<= Error: userlist:php !!!
    }
}

before:

<html>
...

The PHP functions that send or modify the HTTP headers must be executed before the requested page has started to be sent to the user.

Additional information about the error: - headers already sent

An HTTP message consists of a header – Header and a body – Body that are sent in this order to the client – Client . At the moment the Body is sent, the Header cannot be sent anymore.

If you then try to call the header() function after HTML has been sent, you will get the famous error: Cannot modify header information - headers already sent .

Not only does the header () function modify the Header but also the following functions:

Other examples which also produce an error before sending the Header :

  • Spaces before opening _<?php
  • Spaces after closing ?>_
  • Use UTF-8 with BOM
  • Show / add information / content or error messages:
    HTML , echo , print , var_dump() … etc

Examples of wrong codes:

<?php
echo "Foo Bar"; // Mostrar contenido echo
setcookie("Foo", "Bar");

 <?php // Espacio antes del "<?php"
session_start();
?>

<html> <!-- Mostrando contenido HTML -->
<head>
<?php
session_start();
?>
Scroll to Top