PHP.mk документација

SessionHandlerInterface

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

class.sessionhandlerinterface.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека class.sessionhandlerinterface.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
SessionHandlerInterface

Референца за `class.sessionhandlerinterface.php` со подобрена типографија и навигација.

class.sessionhandlerinterface.php

Класата SessionHandlerInterface

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

Вовед

SessionHandlerInterface е интерфејс кој ги дефинира минималните прототипи за креирање на прилагоден ракувач на сесии. За да се предаде прилагоден ракувач на сесии на session_set_save_handler() е интерфејс кој дефинира опционални методи за креирање на прилагоден ракувач на сесии. За да се проследи прилагоден ракувач на сесии до OOP користејќи го неговиот

Ве молиме имајте предвид дека методите за повикување на оваа класа се дизајнирани да бидат повикани внатрешно од PHP и не се наменети да бидат повикани од кориснички код.

Синопсис на интерфејсот

interface SessionHandlerInterface {
/* Методи */
public close(): bool
public destroy(string $id): bool
public gc(int $max_lifetime): int|false
public open(string $path, string $name): bool
public read(string $id): string|false
public write(string $id, string $data): bool
}

Примери

Пример #1 Пример користејќи SessionHandlerInterface

Следниот пример обезбедува складирање на сесии базирано на датотеки, слично на стандардниот ракувач за зачувување на PHP сесиите files. Овој пример лесно може да се прошири за да покрие складирање во база на податоци користејќи го вашиот омилен PHP поддржан систем за бази на податоци.

Забележете дека го користиме ООП прототипот со session_set_save_handler() и ја регистрираме функцијата за исклучување користејќи го знамето на параметарот на функцијата. Ова генерално се препорачува при регистрирање објекти како ракувачи за зачувување на сесии.

Безбедност: стандардниот сет на знаци

За краткост, овој пример изоставува валидација на влезот. Сепак, $id параметрите се всушност вредности дадени од корисникот кои бараат соодветна валидација/санитизација за да се избегнат ранливости, како што се проблеми со преминување на патеки. Затоа, не го користете овој пример непроменет во продукциски средини.

<?php
class MySessionHandler implements SessionHandlerInterface
{
private
$savePath;

public function
open($savePath, $sessionName): bool
{
$this->savePath = $savePath;
if (!
is_dir($this->savePath)) {
mkdir($this->savePath, 0777);
}

return
true;
}

public function
close(): bool
{
return
true;
}

#[
\ReturnTypeWillChange]
public function
read($id)
{
return (string) @
file_get_contents("$this->savePath/sess_$id");
}

public function
write($id, $data): bool
{
return
file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
}

public function
destroy($id): bool
{
$file = "$this->savePath/sess_$id";
if (
file_exists($file)) {
unlink($file);
}

return
true;
}

#[
\ReturnTypeWillChange]
public function
gc($maxlifetime)
{
foreach (
glob("$this->savePath/sess_*") as $file) {
if (
filemtime($file) + $maxlifetime < time() && file_exists($file)) {
unlink($file);
}
}

return
true;
}
}

$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();

// proceed to set and retrieve values by key from $_SESSION

Содржина

Белешки од корисници 8 белешки

ohcc на 163 dot com
пред 8 години
As of PHP 7.0, you can implement SessionUpdateTimestampHandlerInterface to 
define your own session id validating method like validate_sid and the timestamp updating method like update_timestamp in the non-OOP prototype of session_set_save_handler().

SessionUpdateTimestampHandlerInterface is a new interface introduced in PHP 7.0, which has not been documented yet. It has two abstract methods: SessionUpdateTimestampHandlerInterface :: validateId($sessionId) and SessionUpdateTimestampHandlerInterface :: updateTimestamp($sessionId, $sessionData).

<?php
    /*
       @author Wu Xiancheng
       Code structure for PHP 7.0+ only because SessionUpdateTimestampHandlerInterface is introduced in PHP 7.0
       With this class you can validate php session id and update the timestamp of php session data
       with the OOP prototype of session_set_save_handler() in PHP 7.0+
    */
    class PHPSessionXHandler implements SessionHandlerInterface, SessionUpdateTimestampHandlerInterface {
        public function close(){
            // return value should be true for success or false for failure
            // ...
        }
        public function destroy($sessionId){
            // return value should be true for success or false for failure
            // ... 
        }
        public function gc($maximumLifetime){
            // return value should be true for success or false for failure
            // ...
        }
        public function open($sessionSavePath, $sessionName){
            // return value should be true for success or false for failure
            // ...
        }
        public function read($sessionId){
            // return value should be the session data or an empty string
            // ...
        }
        public function write($sessionId, $sessionData){
            // return value should be true for success or false for failure
            // ...
        }
        public function create_sid(){
            // available since PHP 5.5.1
            // invoked internally when a new session id is needed
            // no parameter is needed and return value should be the new session id created
            // ...
        }
        public function validateId($sessionId){
            // implements SessionUpdateTimestampHandlerInterface::validateId()
            // available since PHP 7.0
            // return value should be true if the session id is valid otherwise false
            // if false is returned a new session id will be generated by php internally
            // ...
        }
        public function updateTimestamp($sessionId, $sessionData){
            // implements SessionUpdateTimestampHandlerInterface::validateId()
            // available since PHP 7.0
            // return value should be true for success or false for failure
            // ...
        }
    }
?>
ohcc на 163 dot com
пред 8 години
The non-OOP prototype of session_set_save_handler() supports validate_sid and update_timestamp as of PHP 7.0 while the OOP prototype doesn't even in PHP 7.2. However the OOP prototype does support create_sid since PHP 5.5.1.

validate_sid($sessionId)
  This callback is to validate $sessionId. Its return value should be true for valid session id $sessionId or false for invalid session id $sessionId. If false is returned, a new session id is generated to replace the invalid session id $sessionId.

update_timestamp($sessionId)
  This call back is to update timestamp, and its return value should be true for success or false for failure.
ohcc на 163 dot com
пред 8 години
As of PHP 5.5.1, another method create_sid() is supported. It will be called when session_regenerate_id() is invoked.

SessionHandlerInterface {
    /* Methods */
    abstract public bool close ( void )
    abstract public bool create_sid ( void )    
    abstract public bool destroy ( string $session_id )
    abstract public bool gc ( int $maxlifetime )
    abstract public bool open ( string $save_path , string $session_name )
    abstract public string read ( string $session_id )
    abstract public bool write ( string $session_id , string $session_data )
}
warxcell на gmail точка ком
пред 13 години
You should prepend <b>\</b> before class name, to tell php its from root namespace.
avenidagez на foro5 точка ком
пред 11 години
Note that session_start( ) calls open then read and the class returns true for open and the value of session or empty for read.
Well, then there is no catch for errors, this is, session_start() must return false on failure, but that is not the case for the class implementation on method open, no matter if you return true or false or whatever from open, it is ignored by session_start() function and proceeds to read method
A bug?, if open returns false, session_start() should stop the next step (read) and return itself false

if(session_start()) ...code
else exit( );

So forget about session_start() return value, you need to implement an error catch routine and exit() in case of failure on open method
Victor H
пред 7 години
Your custom session handler should not contain calls to any of the session functions, such as session_name() or session_id(), as the relevant values are passed as arguments on various handler methods. Attempting to obtain values from alternative sources may not work as expected.
ohcc на 163 dot com
пред 6 години
If you want to use type declarations in your own session handling class, don't "implements" the SessionHandlerInterface, SessionIdInterface, or SessinUpdateTimestampInterface, otherwise you will get a fatal error saying that declaration of the class method must be compatible with the interface method.

a bad example
<?php
    class SessionWuXianchengHandler implements SessionHandlerInterface {        
        public function open(string $sessionPath, string $sessionName) : bool {
        }
        ......
    }
?>

a good example
<?php
    class SessionWuXianchengHandler {
        public function open(string $sessionPath, string $sessionName) : bool {
        }
        ......
    }
?>
StanE
пред 10 години
I think there is a small "error" in the example of the class MySessionHandler in method gc(). It uses the function filemtime() whose return value is cached by PHP. Add the following line inside the foreach block in the gc() method:

clearstatcache(true, $file);
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.