user3021621
user3021621

Reputation: 341

function session_destroy kills/doent kills the session array

here are 3 php scripts: the first file where I set the session:

<?php session_start(); // store session data
$_SESSION["username"] = "joshmathews" ;
$_SESSION["name"] = "josh" ; ?> 

the second script where I first output the code and then I destroy the session and then start the session again:

<?php session_start(); 
echo "<br>Username = " . $_SESSION["username"];
echo "<br> name= " . $_SESSION["name"] ;
echo "<br>" . session_id() ; 
//session_id(200) ; //
 session_destroy() ; 
echo "<br>Username = " . $_SESSION["username"]; 
echo "<br> name= " . $_SESSION["name"] ; 
echo "<br>" .session_id() ;

the third script where I only output the session array:

<?php 
session_start() ; 
echo $_SESSION['name'] ; 
echo "<br>" . session_id() ; ?> 

now in the second script if I include the line where I change the session id I can still access the session array in the third code but if I exclude the change of the session id then I cant acess the session array in the third code. why??????

Upvotes: 0

Views: 85

Answers (2)

Chris Bornhoft
Chris Bornhoft

Reputation: 4301

session_id() needs to be called BEFORE session_start() in order for the ID to be properly set.

See the manual for session_id() . Under the parameter $id it states this.

If id is specified, it will replace the current session id. session_id() needs to be called before session_start() for that purpose.

Also when setting the $id, you should pass it as a string for uniformity purposes:

session_id('200');

Upvotes: 0

Vitaly Dyatlov
Vitaly Dyatlov

Reputation: 1872

Because when you call session_id(200) - it is changing your current session to another one and you're destroying a newly created session.

Read here more: http://www.php.net/manual/en/function.session-id.php

If id is specified, it will replace the current session id. session_id() needs to be called before session_start() for that purpose

Upvotes: 2

Related Questions