Home » Php » html – php multiple headers

html – php multiple headers

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m using a header to show succes message after submit. I also want to redirect the user to the index.php page after 5 seconds, but somehow it doesn’t work.

if(mysqli_query($link, $sql)){
    header("Location: addbusiness.php?message=<div class='alert alert-success' role='alert' style='text-align: center; margin-bottom: 50px;'>Succes.</div>");
    header( "refresh:5;url=index.php" );
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
How to&Answers:

You simply can’t do location and refresh at the same time, so you have to separate both headers, i.e. the refresh should be part of the page where you are displaying the message. Also, there is no reason (it’s a bad practice actually) to pass entire HTML into the URL, better use some ID, like:

db.php

<?php
    if(mysqli_query($link, $sql)){
        header("Location: addbusiness.php?message=1");
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }
?>

addbusiness.php

<?php
    if(!empty($_GET['message'])){
        if($_GET['message'] == 1){
            header( "refresh:5;url=index.php" );
            echo "<div class='alert alert-success' role='alert' style='text-align: center; margin-bottom: 50px;'>Success.</div>";
        }else{
            //do something else
        }
    }
?>

Based on such a condition, you also will avoid the refresh every time when visits addbusiness.php

Of course, in any case you have to ensure that there is no any HTML output to the browser before calling header(). In both pages.