PHP未设置会话不起作用

My PHP script to unset session variable is not working.

I need to call a PHP file destroy.php which contains code to unset session variable from ajax, everything is working fine except session clear.

I'm posting my code for clearing session variable, please point out my error.

jQuery Code:

$.ajax
                    ({
                        type: "POST",
                        url: "SubmitReview.php",
                        data: dataString,
                        cache: false,

                        success: function(response)
                        {
                            $.fn.destroySession();
                            $('body').animate({scrollTop:0}, 500);
                            $('body').children(':not(div.ErrorMessageContainer)').fadeTo(500, 0.1);
                            $('div.ErrorMessageContainer').html(response).fadeIn(500).delay(5000).fadeOut(500);
                            setTimeout(function()
                            {
                                $('body').children(':not(div.ErrorMessageContainer)').fadeTo(500, 1);
                            }, 5400);
                            setTimeout(function()
                            {
                                window.location.href = "Thanks.php";
                            }, 5600);
                        }
                    });

$.fn.destroySession = function()
            {
                $.post("Destroy.php");
            }

destroy.php:

<?php

if(isset($_SESSION['MN']))
{
    $_SESSION['MN'] = array();
    unset($_SESSION['MN']);
}

?>

Put session_start() on first line.

<?php
session_start();

if(isset($_SESSION['MN']))
{
    $_SESSION['MN'] = array();
    unset($_SESSION['MN']);
}

As stated in comments, you did not start the session and is required to be inside all files using sessions.

Therefore, add session_start(); at the top and underneath your opening PHP tag.

Reference:

Add error reporting to the top of your file(s) which will help find errors.

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Then the rest of your code

Sidenote: Displaying errors should only be done in staging, and never production.


"why to again start session" - Because, session_start(); is required to reside in the file even though you want to unset it (that's just how they built it at PHP.net).

<?php
session_start();

if(isset($_SESSION['MN']))
{
    $_SESSION['MN'] = array();
    unset($_SESSION['MN']);
}