嗨,我想在php中添加一些功能到session_start函数。我知道我可以写一个自定义函数来取代session_start(),但这走得太远了。我只是想有一些额外的代码触发,而不是删除旧的代码。
编辑:我特别想把会话ID写入sql表
您可以简单地在您使用的session_start()
周围创建一个函数包装器。
function my_session_start() {
session_start();
$session_id = session_id();
// write $session_id to database by whatever method you choose
}
// usage
my_session_start();
或者如果你想扩展sessionHandler你可以这样做:
class mySessionHandler extends sessionHandler {
// perhaps a property to store db connection or DB object as needed for writing session id to database
protected $db = null;
public function __construct($db = null) {
if(is_null($db)) {
throw new Exception('Give me a database');
}
// maybe some other validation (could also use type hinting in parameter
$this->db = $db;
}
public function open($save_path, $session_id) {
parent::open($save_path, $session_id);
// not shown - use $this->db to insert $session_id to database
}
}
// usage
$session_handler = new mySessionHandler($db);
session_set_save_handler($session_handler, true);
session_start();
这里您只重写open()
方法来将会话id添加到数据库。