PHP and the function header (location:)

  Tags: , ,

I have a Hostgator hosting in which I always have the same problem when using the php header function to redirect, for example: header ("Location: index.php"); If I do it in xampp, there are no problems and everything works fine, but if I upload it to the hosting, I always receive the warning that says "headers already sent ... blah blah blah". It always happens, I just use the header function ("Location: file.php") I receive the warning and it does not redirect me. How can I solve it?

Here goes my code

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Lista de Precios</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<style>
    body {
        margin-top: 20px;
        background-image: url('img/fondo-hawaii.jpg');
        background-repeat: no-repeat;
        background-attachment: fixed;
        background-position: center;
        background-size: cover;
    }

    table, tr, td {
          border: 1px solid black;
          border-collapse: collapse;


     }
     tr td {
      max-width: 20%;
     }
     tr td:nth-child(1) {
  max-width: 10%;
}
     .table-striped > tbody > tr:nth-child(2n) > td, .table-striped > tbody > tr:nth-child(2n) > th {
   background-color: #fff;
    }
    .table-hover tbody tr:hover td, .table-hover tbody tr:hover th {
  background-color: #D3D3D3;
}
 .primera_fila {
    font-weight: bold;
    background-color: #D4D4D4;
 }   
</style>
</head>

<body>
<div class="container">
 <div class="row">
    <div class="col-sm-4 col-md-2"></div>
    <div class="col-sm-4 col-md-8">
    <img src="img/logo-halo-hawaii.jpg" class="img-responsive" alt="">
   &nbsp;
     </div>
     <div class="col-sm-4 col-md-2"></div>
 </div>
<h1 style="text-align: center;">ACTUALIZAR</h1>

<?php
  include("conexion.php");
  if (!isset($_POST["bot_actualizar"])) {
    $id=$_GET["id"];
    $nombre=$_GET["nombre"];
    $precio=$_GET["precio"];
    $fabricante=$_GET["fabricante"];  
  }else{
    $id=$_POST["id"];
    $nombre=$_POST["nombre"];
    $precio=$_POST["precio"];
    $fabricante=$_POST["fabricante"];
    $sql="UPDATE precios SET nombre=:minom, precio=:mipre, fabricante=:mifab WHERE id=:miid";
    $resultado=$base->prepare($sql);
    $resultado->execute(array(":miid"=>$id, ":minom"=>$nombre, ":mipre"=>$precio, ":mifab"=>$fabricante));
    header("Location:index.php");
  }

?>
<p>&nbsp;</p>
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  <table  class="table  table-hover table-striped" style="width: 60%;" align="center">
    <tr>
      <td></td>
      <td><label for="id"></label>
      <input type="hidden" name="id" id="id" value="<?php echo $id ?>"></td>
    </tr>
    <tr>
      <td>Nombre</td>
      <td><label for="nombre"></label>
      <input type="text" name="nombre" id="nombre" value="<?php echo $nombre ?>"></td>
    </tr>
    <tr>
      <td>Apellido</td>
      <td><label for="precio"></label>
      <input type="text" name="precio" id="precio" value="<?php echo $precio ?>"></td>
    </tr>
    <tr>
      <td>Dirección</td>
      <td><label for="fabricante"></label>
      <input type="text" name="fabricante" id="fabricante" value="<?php echo $fabricante ?>"></td>
    </tr>
    <tr>
      <td colspan="2"><input type="submit" name="bot_actualizar" id="bot_actualizar" value="Actualizar"></td>
    </tr>
  </table>
</form>
<p>&nbsp;</p>
</div>
</body>
</html>

On github: https://github.com/ashcrimson/halohawaii/blob/master/editar.php


Solution to “headers already sent” while using php “location:”

Contrary to what some answers say, you should not hide the warning . It’s there for a reason and it gives you a clear description of why it does not work. The warning you are receiving is because you are sending headers after sending the body of the HTML … it’s too late.


Redirect with header (‘Location: …’)

header()It sends the HTTP headers and it must be the first thing the server sends , before any other declaration, without even blank lines before. Also, for some browsers, the URL to which you want to redirect can not be a relative path, it must be an absolute path .

header('Location: http://tuweb.com/pagina.html');
die();

And with die()we finish immediately the execution of the script, avoiding that more exit is sent to the client. However, it is best to send a message notifying you that you have been redirected with a link to follow, in case automatic redirection does not work. For example

header('Location: http://tuweb.com/pagina.html');
echo "El recurso se ha movido hacia <a href=\"http://tuweb.com/pagina.html\">aquí</a>."
die();

For example, if we wanted to redirect to a page within the current route, regardless of the route:

$host = $_SERVER['HTTP_HOST'];
$ruta = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$html = 'pagina.html';
$url = "http://$host$ruta/$html";
header("Location: $url");
echo "El recurso se ha movido hacia <a href=\"$url\">aquí</a>."
die();

In your case, the PHP code should be at the beginning of the file.


Note: Some hosting services send headers on their own, making it impossible to redirect using headers. The alternatives are:

With a META tag in HTML

<meta http-equiv="Location" content="http://tuweb.com/pagina.html"/>

or through JavaScript

window.location.replace("http://tuweb.com/pagina.html");

The most robust recommendation is that you use all the variants, in case one fails. For example

$host = $_SERVER['HTTP_HOST'];
$ruta = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$html = 'pagina.html';
$url = "http://$host$ruta/$html";

header("Location: $url");
include redirect.php;
die();

And the code redirect.phpwould be:

<html>
<head>
<meta http-equiv="Location" content="
<?= $url ?>"/>
<script type="text/javascript">
window
.location.replace("<?= $url ?>");
</script>
</head>

<body>
El recurso se ha movido hacia <a href=”
<?= $url ?>“>aquí</a>.
</body>
<html>

Few more thoughts and answers prevail for this issue:

It’s a matter of putting the code phpbefore the html.

<?php
include("conexion.php");
if(!isset($_POST["bot_actualizar"])) {
    $id         = $_GET["id"];
    $nombre     = $_GET["nombre"];
    $precio     = $_GET["precio"];
    $fabricante = $_GET["fabricante"];
}
else {
    $id         = $_POST["id"];
    $nombre     = $_POST["nombre"];
    $precio     = $_POST["precio"];
    $fabricante = $_POST["fabricante"];
    $sql        = "UPDATE precios SET nombre=:minom, precio=:mipre, fabricante=:mifab WHERE id=:miid";
    $resultado  = $base->prepare($sql);
    $resultado->execute(array(":miid"  => $id,
                              ":minom" => $nombre,
                              ":mipre" => $precio,
                              ":mifab" => $fabricante
    ));
    header("Location:index.php");
}
?>
<!doctype html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- //... resto del código -->

That should solve it.

And checking the rest of the files, you should change it in all to avoid other errors. The code that you execute does not need to be mixed with the html.

One more thoughts and answers prevail for this issue:

Although the function header () is not to show a serious error unless it is not written correctly or not in the correct way is something similar with the require when the file does not exist this shows a serious error and does not run the application.

Could you show the code where the header () function is located to analyze the error more thoroughly?

Remember that header () must be called before displaying anything on the screen, HTML tags, blank lines from a file or from PHP. It is a common error to read code with functions such as include or require, or other types of file access functions that include spaces or blank lines that are displayed before calling the header () function The same problem occurs when a single PHP / HTML file is used.

<html>
<?php
/* Esto producirá un error. Fíjese en el html
 * que se muestra antes que la llamada a header() */
 header('Location: http://www.example.com/');
?>

At the beginning of the file add

<?php ob_start() ?>

At the end

<?php ob_end_flush();?>

 

LEAVE A COMMENT