Skip to content

Commit 40f3d76

Browse files
committed
fix: Session::markAsTempdata() adding wrong TTL
1 parent 3329576 commit 40f3d76

File tree

2 files changed

+34
-25
lines changed

2 files changed

+34
-25
lines changed

system/Session/Session.php

Lines changed: 17 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -817,39 +817,31 @@ public function removeTempdata(string $key)
817817
*/
818818
public function markAsTempdata($key, int $ttl = 300): bool
819819
{
820-
$ttl += Time::now()->getTimestamp();
820+
$time = Time::now()->getTimestamp();
821+
$keys = is_array($key) ? $key : [$key];
821822

822-
if (is_array($key)) {
823-
$temp = [];
824-
825-
foreach ($key as $k => $v) {
826-
// Do we have a key => ttl pair, or just a key?
827-
if (is_int($k)) {
828-
$k = $v;
829-
$v = $ttl;
830-
} elseif (is_string($v)) {
831-
$v = Time::now()->getTimestamp() + $ttl;
832-
} else {
833-
$v += Time::now()->getTimestamp();
834-
}
823+
if (array_is_list($keys)) {
824+
$keys = array_fill_keys($keys, $ttl);
825+
}
835826

836-
if (! array_key_exists($k, $_SESSION)) {
837-
return false;
838-
}
827+
$tempdata = [];
839828

840-
$temp[$k] = $v;
829+
foreach ($keys as $sessionKey => $timeToLive) {
830+
if (! array_key_exists($sessionKey, $_SESSION)) {
831+
return false;
841832
}
842833

843-
$_SESSION['__ci_vars'] = isset($_SESSION['__ci_vars']) ? array_merge($_SESSION['__ci_vars'], $temp) : $temp;
844-
845-
return true;
846-
}
834+
if (is_int($timeToLive)) {
835+
$timeToLive += $time;
836+
} else {
837+
$timeToLive = $time + $ttl;
838+
}
847839

848-
if (! isset($_SESSION[$key])) {
849-
return false;
840+
$tempdata[$sessionKey] = $timeToLive;
850841
}
851842

852-
$_SESSION['__ci_vars'][$key] = $ttl;
843+
$_SESSION['__ci_vars'] ??= [];
844+
$_SESSION['__ci_vars'] = [...$_SESSION['__ci_vars'], ...$tempdata];
853845

854846
return true;
855847
}

tests/system/Session/SessionTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -476,6 +476,23 @@ public function testSetTempDataArraySingleTTL(): void
476476
$this->assertLessThanOrEqual($_SESSION['__ci_vars']['baz'], $time + 200);
477477
}
478478

479+
/**
480+
* @see https://github.com/codeigniter4/CodeIgniter4/issues/9534
481+
*/
482+
public function testSetTempDataOnArrayData(): void
483+
{
484+
$session = $this->getInstance();
485+
$session->start();
486+
487+
$time = time();
488+
489+
$session->setTempdata(['foo1' => 'bar1'], null, 200);
490+
$session->setTempdata('foo2', 'bar2', 200);
491+
492+
$this->assertLessThanOrEqual($_SESSION['__ci_vars']['foo1'], $time + 200);
493+
$this->assertLessThanOrEqual($_SESSION['__ci_vars']['foo2'], $time + 200);
494+
}
495+
479496
/**
480497
* @see https://github.com/codeigniter4/CodeIgniter4/pull/9536#discussion_r2051798869
481498
*/

0 commit comments

Comments
 (0)