yangakw yangakw

cookie替代session

in 代码read (31) 文章转载请注明来源!

修改后的代码

<?php

namespace visualCaptcha;

class Session {
    private $namespace = '';
    private static $data = [];
    private static $native = false;

    public function __construct( $namespace = 'visualcaptcha' ) {
        $this->namespace = $namespace;
    }

    public function clear() {
        if ( isset( $_COOKIE[ $this->namespace ] ) ) {
            self::$data = unserialize($_COOKIE[ $this->namespace ]);
        }
    }

    public static function openNative(){
        self::$native=true;
    }
    public function get( $key ) {
        if ( self::$native ) {
            $this->clear();
        }
        if ( isset( self::$data[ $key ] ) ) {
            return self::$data[ $key ];
        }
        return null;
    }

    public function set( $key, $value ) {
        self::$data[ $key ] = $value;
        setCookie(
            $this->namespace,
            serialize(self::$data),
            time()+3600,
            "/"
        );
    }

};

?>

原始代码

<?php

namespace visualCaptcha;

class Session {
    private $namespace = '';

    public function __construct( $namespace = 'visualcaptcha' ) {
        $this->namespace = $namespace;
    }

    public function clear() {
        $_SESSION[ $this->namespace ] = Array();
    }

    public function get( $key ) {
        if ( !isset( $_SESSION[ $this->namespace ] ) ) {
            $this->clear();
        }

        if ( isset( $_SESSION[ $this->namespace ][ $key ] ) ) {
            return $_SESSION[ $this->namespace ][ $key ];
        }

        return null;
    }

    public function set( $key, $value ) {
        if ( !isset( $_SESSION[ $this->namespace ] ) ) {
            $this->clear();
        }

        $_SESSION[ $this->namespace ][ $key ] = $value;
    }
};

?>
jrotty WeChat Pay

微信打赏

jrotty Alipay

支付宝打赏

文章二维码

扫描二维码,在手机上阅读!

发表新评论
博客已运行
© 2017 yangakw
PREVIOUS NEXT
雷姆
拉姆