Header trampling Echo

4

I'm trying to use the following code:

echo "<script>alert('Erro. Tente novamente.');</script>";   
$insertGoTo ="pág.php";
header("Location: $insertGoTo");

However, running code header() runs over echo and the alert message is not displayed.

How can I make it display the message before the redirect of header() ?

    
asked by anonymous 25.08.2014 / 23:41

2 answers

6
  

PHP-HEADER Remember that header () must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions or other file access function, and have spaces or blank lines that are output before header () is called. The same problem exists when using a single PHP / HTML file.

The header's are always sent before exits, so if you use Location + echo the page will be redirected without displaying content. >

In addition to the javascript alternative, which does not guarantee functionality if it is disabled in the user's browser, you can use the header with refresh , or meta-refresh , or combine the 3 options, ensuring functionality and accessibility:

•[PHP]  | header( "refresh:5;url={$insertGoTo}" )
•[HTML] | <meta http-equiv="refresh" content="0; url=http://example.com/" />
•[JS]   | Countdown exibindo o tempo restante para o redirecionamento com link direto


#Alternative 1

using header of PHP itself.

header( "refresh:5;url={$insertGoTo}" );
echo 'você será redirecionado...';


#Alternative 2

An alternative is to use meta-refresh , which ensures that the user will be redirected even if javascript is disabled.

<meta http-equiv="refresh" content="0; url=http://example.com/" />


HTML5-based example

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="refresh" content="0; url=<?php echo $insertGoTo;?>" />
    <title>Title</title>
</head>
<body>
    <script>alert('Erro. Tente novamente.');</script>
    <p>Você será redirecionado em 5 segundos.</p>
</body>
</html>
    
26.08.2014 / 00:18
5

If you want the user to read then you have to do this redirect on the client side as well.

Once the alert stops the script, the next line of javascript will be run when the window closes using for example the window.location , or window.location.replace (which has the advantage of not polluting the history with the same page ).

Example:

echo "<script>
  alert('Erro. Tente novamente.');
  window.location.replace('pág.php');
</script>"; 
    
25.08.2014 / 23:46