gpt4 book ai didi

session - PHP:在 session 中断 session 中存储闭包

转载 作者:搜寻专家 更新时间:2023-10-31 22:10:10 25 4
gpt4 key购买 nike

Update: solved

I finally figured out my problem (I think). I'm pretty sure the issue is that closures cannot be serialized, which means they cannot be stored in the session. The next issue then is that PHP was not returning a very useful error, and was breaking in an unexpected way, instead of just telling me that I couldn't serialize a closure.


我将 session 数据存储在 mysql 数据库中。我的应用程序的那部分已经到位并且运行良好了很长一段时间。今天我试图在 session 中存储一个闭包(即匿名函数),这打破了我原本表现良好的 session 。

我的 session 管理由一个对象处理,当 PHP 试图销毁该对象时,该对象会自动调用 session_write_close()。我这样做是为了否则,当 PHP 尝试关闭 session 时,我的数据库连接(一个 mysqli 对象)已经被破坏。

我像这样接管 session 处理:

// set the session save handler
session_set_save_handler(
array( $this, '_open' ),
array( $this, '_close' ),
array( $this, '_read' ),
array( $this, '_write' ),
array( $this, '_destroy' ),
array( $this, '_clean' )
);

这是非常标准的。处理 session 关闭的部分是这样的:

public function __destruct()
{
// this variable will only be destroyed when the script is closing
// at this point it is safe to close the session
// if we wait for php to close the session then we will
// have lost the database connection, so we do it now

session_write_close();
}

// write session data
public function _write( $sid, $data )
{
// run query to write to database
$now = NOW;
$stmt = $this->mysqli->prepare( "REPLACE INTO $this->table (sid,time,data) VALUES (?,?,?)" );
$stmt->bind_param( 'sis', $sid, $now, $data );

// execute
$success = $stmt->execute();

// close
$stmt->close();

// and return
return $success;
}

// close session store
public function _close()
{
// close the database connection
$this->mysqli->close();

return true;
}

几个打印函数显示,通常情况下这就像您想象的那样工作:调用 __destruct() 函数,它调用 session_write_close(),紧接着调用 _write() 和 _close()。但是,当我将闭包存储到 session 中时:

$test = function($name)
{
print "Hello $name";
};

$_SESSION['test'] = $test;

一切都崩溃了。 __destruct() 像以前一样被调用,但执行永远不会到达 _write() 或 _close() 函数。相反,我收到了这些消息:

Warning: session_write_close() [function.session-write-close]: Failed to write session data (user). Please verify that the current setting of session.save_path is correct (/var/lib/php/session) in /var/www/vhosts/ambida.com/httpdocs/includes/core/session_handler.php on line 48

Fatal error: Exception thrown without a stack frame in Unknown on line 0

这真的没有意义。看起来它已经恢复到默认 session 处理程序,这当然会失败,因为 tmp 文件从未打开(因为我的函数接管了打开 session )。我不明白为什么在 session 中存储闭包会导致发生这种恢复,或者为什么这通常会中断。任何帮助将不胜感激。

最佳答案

这现在可以通过使用 Jeremy Lindblom 的 SuperClosure 来实现。该软件包可以在他的 github 上找到:https://github.com/jeremeamia/super_closure

关于session - PHP:在 session 中断 session 中存储闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13768543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com