tags:

views:

569

answers:

5

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 popup 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.";
?>
+6  A: 

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.

Andrew G. Johnson
+1  A: 

Yeah, you're going to want to do

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

or

if( isset($_GET['destroy']) )
Magic Hat
+4  A: 

By the way you can use

$_REQUEST['destroy']

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

Pat
Not really a good practice. It's important to make sure your variables come from the expected source.
Álvaro G. Vicario
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.
Pat
A: 

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

Pierre Spring
+2  A: 

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