1

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.";
?>

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

By the way you can use

$_REQUEST['destroy']

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

2 Comments

Not really a good practice. It's important to make sure your variables come from the expected source.
Really? why is it important? If someone can fake a GET they can fake a POST as easily. I think it does not mater if your variables come from GET or POST you should treat both as equally untrusted regardless.
2

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();

Comments

1

Yeah, you're going to want to do

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

or

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

Comments

0

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 ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.