|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2005-05-02 11:14 UTC] bugs dot php dot net at enca dot cz
Description:
------------
In this testcase the "write" function is not called. If you remove line with "unset", the write function is called properly. If you delete whole foreach cycle and use
"unset($_SESSION['A']);" instead, the "write" function si also called - as expected. This bug appear only when you call "unset" inside foreach cycle.
My environment:
MS Windows Server 2003 SE (Windows NT 5.2 build 3790)
Apache/2.0.53 (Win32) PHP/5.0.4
Smilar (but not exactly same) bug is described as #32564, but it is in the No feedback status and there is no way (for me) to change this status. I hope that this "reproduce code" is much better then codes from #32564
I can provide more information if you ask for them.
Reproduce code:
---------------
<?php
function foo(){return(true);}
function read($id){
return 'A|s:1:"a";B|s:1:"b";';
}
function write($id, $sess_data){
print "I'm writing this data: $sess_data\n";
return true;
}
header('Content-Type: text/plain');
session_set_save_handler("foo", "foo", "read", "write", "foo", "foo");
session_start();
print_r($_SESSION);
foreach($_SESSION as $lsKey => $lsVal){
if($lsKey != 'A'){
unset($_SESSION[$lsKey]); //<<<<<<<< if you comment this line, the write function is called properly
}
}
print_r($_SESSION);
?>
Expected result:
----------------
Array
(
[A] => a
[B] => b
)
Array
(
[A] => a
)
I'm writing this data: A|s:1:"a";
Actual result:
--------------
Array
(
[A] => a
[B] => b
)
Array
(
[A] => a
)
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Fri Dec 19 01:00:01 2025 UTC |
Workaround for the reported problem foreach-iterating $_SESSION with unset() inside the loop: $unset_collection = array(); // 1. Collect the Session-Variable to unset, // because unset inside the foreach-loop will not work. foreach ($_SESSION as $sessvar => $sessval) { if ($sessvar != "A") { array_push($unset_collection,$sessvar); } } // 2. Unset the session variables outside the foreach foreach ($unset_collection as $sessvar) { unset($_SESSION[$sessvar]); } Comment: Changing a loop control variable inside of a loop is not good programming style. Just this happens, if adding or removing a $_SESSION variable inside of a foreach for $_SESSION. The solution is extracting the the processes of unseting or adding outside of that loop.