使用会话的php消息

I am try to develop flash message using sessions in php suppose on successfully delete query I am setting

$_SESSION["msg"]="record deleted successfully";
header("location:index.php");

and I have the following script on all pages which checks if msg variable is available it echo its value as below

if(isset($_SESSION["msg"]) && !empty($_SESSION["msg"]))
        {
            $msg=$_SESSION["msg"];
            echo "<div class='msgbox'>".$msg."</div>";
            unset($_SESSION['msg']); //I have issue with this line.
        }

if I comment

unset($_SESSION['msg']);

message is being displayed, but with this line message is not being displayed
what am I doing wrong, or any alternative.

You can simply set your session empty or null instead of unset it. Just do:

$_SESSION['msg']=NULL;

Or

$_SESSION['msg']="";

You are saying that you have that script on every page. So my guess is that after you make header("location:index.php"); your code continues to run - your message is displayed and unset (you don't see it because of redirect to index.php). When you are redirected to index.php your message is already unset.

Try adding exit; after header("location:index.php");.

Edit: I will add two examples with one working and one not. To test you need access test page with following link - /index.php?delete=1

In this example you will never see message. Why? Because header function does not stop code execution. After you set your session variable and set your redirect your code continues to execute. That means your message is printed and variable unset too. When code finishes only than redirect is made. Page loads and nothing is printed because session variable was unset before redirect.

<?php
session_start();
// ... some code
if ($_GET['delete']==1) {
    $_SESSION["msg"] = "record deleted successfully";
    header("location: index.php");
}
// ... some code
if (isset($_SESSION["msg"]) && !empty($_SESSION["msg"])) {
    $msg = $_SESSION["msg"];
    echo "<div class='msgbox'>" . $msg . "</div>";
    unset($_SESSION['msg']);
}
// ... some code
?>

But this code probably will work as you want. Note that I have added exit after header line. You set your message, tell that you want redirect and tell to stop script execution. After redirect your message is printed and unset as you want.

<?php
session_start();
// ... some code
if ($_GET['delete']==1) {
    $_SESSION["msg"] = "record deleted successfully";
    header("location: index.php");
    exit;
}
// ... some code
if (isset($_SESSION["msg"]) && !empty($_SESSION["msg"])) {
    $msg = $_SESSION["msg"];
    echo "<div class='msgbox'>" . $msg . "</div>";
    unset($_SESSION['msg']);
}
// ... some code
?>

You clearly said that you have that code (message printing) on all pages. If your code is similar to my example than adding exit should fix your problem.

Another problem might be that you are doing more than one redirect.