Question

I'm trying to do a simple test php script for sessions. Basically it increments a counter (stored in $_SESSION) every time you refresh that page. That works, but I'm trying to have a link to destroy the session which reloads the page with the ?destroy=1 parameter. I've tried a couple of if statements to see if that parameter is set and if so to destroy the session but it doesn't seem to work.

I've even put an if statement in the main body to pop-up a message if the parameter is set - but it doesn't seem to be picked up.

I know I'm doing something silly (I'm a PHP newbie) but I can't seem to find what it is...

See code here:

<?php
if ($_POST['destroy']) {
    session_destroy();
} else {
    session_start();
}    
?>

<html>
    <head>
        <title>Session test</title>
    </head>
    <body>
    <?php
    if (isset($_POST['destroy'])) {
        echo "Destroy set";
    }

    $_SESSION['counter']++;

    echo "You have visited this page " . $_SESSION['counter'] . " times" . "<BR>";
    echo "I am tracking you using the session id " . session_id() . "<BR>";
    echo "Click <a href=\"" . $_SERVER['PHP_SELF'] . "?destroy=1\">here</a> to destroy the session.";
?>
Was it helpful?

Solution

I think you put

$_POST['destroy']

Instead of

$_GET['destroy']

You need to use a form if you'd like to use a $_POST variable. $_GET variables are stored in the URL.

OTHER TIPS

By the way you can use

$_REQUEST['destroy']

which would work regardless if the data is passed in a POST or a GET request.

In the PHP Manual it has code snippet for destroying a session.

session_start();
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
    setcookie(session_name(), '', time()-42000, '/');
}
session_destroy();

Yeah, you're going to want to do

if( $_GET['destroy'] == 1 )

or

if( isset($_GET['destroy']) )

I know I'm doing something silly (I'm a php newbie) but I can't seem to find what it is...

that is how you are going to learn a lot ;) enjoy it ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top