Header running over Echo

Asked

Viewed 2,155 times

5

I’m trying to use the following code:

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

only when executing the code header() runs over the echo and the message of alert is not displayed.

Is there any way I can get him to display the message before the redirect header() ?

2 answers

6


PHP-HEADER
Remember that header() should 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 mistake to read code with include , or require , functions or other file access function, and having 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 shipped before the 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 operation if disabled in the user’s browser, you can use the header with refresh, or the 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 one’s own header of PHP.

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


#Alternative 2

An alternative is to use the meta-refresh, which ensures that the user will be re-directed 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>
  • Damn that haha class! Thanks helped a lot guy!

  • Glad you could help :)

5

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

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

Example:

echo "<script>
  alert('Erro. Tente novamente.');
  window.location.replace('pág.php');
</script>"; 
  • Your way right also guy :D Thanks for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.