Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement PHP independent Session database storage operation class

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to realize the storage operation class of PHP independent Session database. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Go directly to the code:

Class DbSession

{

Const TYPE_INT = 1

Const TYPE_STR = 2

/ * *

* Database configration

*

* @ var array

, /

Private $_ config = array (

'host' = >' 127.0.0.1'

'port' = > 3306

'username' = >' root'

'password' = >' root'

'dbname' = >' db_mylab'

'tablename' = >' tweeters'

'cookie_prefix' = >' mylab_'

'cookiepath' = >' /'

'cookiedomain' = > "

'cookie_timeout' = > 900

);

/ * *

* Table fields type array

*

* @ var array

, /

Private $_ db_fields = array (

'crc32sid' = > self::TYPE_INT

'sessionhash' = > self::TYPE_STR

'idhash' = > self::TYPE_STR

'userid' = > self::TYPE_INT

'ipaddress' = > self::TYPE_STR

'lastactivity' = > self::TYPE_STR

'location' = > self::TYPE_STR

'loggedin' = > self::TYPE_INT

'heartbeat' = > self::TYPE_STR

);

/ * *

* db obj

*

* @ var mysqli object

, /

Private $_ mysqli = null

/ * *

* Weather the session was created or existed previously

*

* @ var bool

, /

Private $_ created = false

/ * *

* Array of changes.

*

* @ var array

, /

Private $_ changes = array ()

/ * *

* @ var bool

, /

Private $_ db_inited = false

/ * *

* session host

*

* @ var string

, /

Private $_ session_host = "

/ * *

* session idhash

*

* @ var string

, /

Private $_ session_idhash = "

Private $_ dbsessionhash = "

Private $_ vars = array ()

Public function _ construct ()

{

$this- > _ dbsessionhash = addslashes ($this- > get_cookie ('sessionhash'))

$this- > _ session_host = substr ($_ SERVER ['REMOTE_ADDR'], 0,15)

# This should * never* change during a session

$this- > _ session_idhash = md5 ($_ SERVER ['HTTP_USER_AGENT']. Self::fetch_substr_ip (self::fetch_alt_ip ())

$this- > _ init_config ()

$this- > init_db ()

$gotsession = false

If ($this- > _ dbsessionhash)

{

$sql ='

SELECT *

FROM'. $this- > _ config ['tablename']. '

WHERE crc32sid ='. Sprintf ('% uplink, crc32 ($this- > _ dbsessionhash)). '

AND sessionhash =''. $this- > _ dbsessionhash. ''

AND idhash =''. $this- > _ session_idhash. ''

AND heartbeat >'. Date (TIMENOW-$this- > _ config ['cookie_timeout']). ''

/ / echo $sql;exit

$result = $this- > _ mysqli- > query ($sql)

$session = $result- > fetch_array (MYSQLI_ASSOC)

If ($session AND ($this- > fetch_substr_ip ($session ['ipaddress']) = = $this- > fetch_substr_ip ($this- > _ session_host))

{

$gotsession = true

$this- > _ vars = $session

$this- > _ created = false

}

}

If ($gotsession = = false)

{

$this- > _ vars = $this- > fetch_session ()

$this- > _ created = true

$gotsession = true

}

If ($this- > _ created = = false)

{

$this- > set ('lastactivity', date (' Y-m-d Havi TIMENOW))

$this- > set ('location', $_ SERVER [' REQUEST_URI'])

}

}

/ * *

* Builds an array that can be used to build a query to insert/update the session

*

* @ return array Array of column name = > prepared value

, /

Private function _ build_query_array ()

{

$return = array ()

Foreach ($this- > _ db_fields AS $fieldname = > $cleantype)

{

Switch ($cleantype)

{

Case self::TYPE_INT:

$cleaned = is_numeric ($this- > _ vars ["$fieldname"])? $this- > _ vars ["$fieldname"]: intval ($this- > _ vars ["$fieldname"])

Break

Case self::TYPE_STR:

Default:

$cleaned = "'". Addslashes ($this- > _ vars ["$fieldname"]). "'"

}

$return ["$fieldname"] = $cleaned

}

Return $return

}

/ * *

* Sets a session variable and updates the change list.

*

* @ param string Name of session variable to update

* @ param string Value to update it with

, /

Public function set ($key, $value)

{

If ($this- > _ vars ["$key"]! = $value)

{

$this- > _ vars ["$key"] = $value

$this- > _ changes ["$key"] = true

}

}

Public function get ($key)

{

Return $this- > _ vars ["$key"]

}

Public function unsetchangedvar ($var)

{

If (isset ($this- > _ changes ["$var"]))

{

Unset ($this- > _ changes ["$var"])

}

}

/ * *

* Fetches a valid sessionhash value, not necessarily the one tied to this session.

*

* @ return string 32-character sessionhash

, /

Static function fetch_sessionhash ()

{

Return hash ('md5', TIMENOW. Rand (1, 100000). Uniqid ())

}

Private function _ init_config ()

{

$registry = Zend_Registry::getInstance ()

$config = $registry- > get ('config')

$this- > _ config ['host'] = $config- > database- > params- > host

$this- > _ config ['port'] = $config- > database- > params- > port

$this- > _ config ['username'] = $config- > database- > params- > username

$this- > _ config ['password'] = $config- > database- > params- > password

$this- > _ config ['dbname'] = $config- > database- > params- > dbname

$this- > _ config ['tablename'] = $config- > database- > session- > tablename

}

/ * *

* initialize database connection

, /

Public function init_db ()

{

If ($this- > _ db_inited)

{

Return true

}

/ / mysqli_report (MYSQLI_REPORT_OFF)

$this- > _ mysqli = new mysqli (

$this- > _ config ['host']

$this- > _ config ['username']

$this- > _ config ['password']

$this- > _ config ['dbname']

$this- > _ config ['port']

);

/ * check connection * /

If (mysqli_connect_errno ())

{

/ / printf ("Connect failed:% sn", mysqli_connect_error ())

/ / echo'in', _ _ FILE__,'on line', _ _ LINE__

Echo "{success: false, errors: {reason: 'Connect failed:". Addslashes (mysqli_connect_error ()) "'}}"

Exit ()

}

$this- > _ mysqli- > query ('set names latin1')

$this- > _ db_inited = true

Return true

}

/ * *

* Fetches an alternate IP address of the current visitor, attempting to detect proxies etc.

*

* @ return string

, /

Static function fetch_alt_ip ()

{

$alt_ip = $_ SERVER ['REMOTE_ADDR']

If (isset ($_ SERVER ['HTTP_CLIENT_IP']))

{

$alt_ip = $_ SERVER ['HTTP_CLIENT_IP']

}

Else if (isset ($_ SERVER ['HTTP_FROM']))

{

$alt_ip = $_ SERVER ['HTTP_FROM']

}

Return $alt_ip

}

/ * *

* Returns the IP address with the specified number of octets removed

*

* @ param string IP address

*

* @ return string truncated IP address

, /

Static function fetch_substr_ip ($ip, $length = null)

{

Return implode ('.', array_slice (explode ('.', $ip), 0, 4-$length))

}

/ * *

* Fetches a default session. Used when creating a new session.

*

* @ param integer User ID the session should be for

*

* @ return array Array of session variables

, /

Public function fetch_session ($userid = 0)

{

$sessionhash = self::fetch_sessionhash ()

$this- > set_cookie ('sessionhash', $sessionhash)

Return array (

'crc32sid' = > sprintf ('% uplink, crc32 ($sessionhash))

'sessionhash' = > $sessionhash

'idhash' = > $this- > _ session_idhash

'userid' = > $userid

'ipaddress' = > $this- > _ session_host

'lastactivity' = > date (' Y-m-d Hrig irig slots, TIMENOW)

'location' = > $_ SERVER [' REQUEST_URI']

'loggedin' = > $userid? 1: 0

'heartbeat' = > date (' Y-m-d Hrig irig slots, TIMENOW)

);

}

Public function get_cookie ($cookiename)

{

$full_cookiename = $this- > _ config ['cookie_prefix']. $cookiename

If (isset ($_ COOKIE [$full_cookiename]))

{

Return $_ COOKIE [$full_cookiename]

}

Else

{

Return false

}

}

Public function set_cookie ($name, $value = ", $permanent = 1, $allowsecure = true)

{

If ($permanent)

{

$expire = TIMENOW + 60 * 60 * 24 * 365

}

Else

{

$expire = 0

}

If ($_ SERVER ['SERVER_PORT'] = =' 443')

{

/ / we're using SSL

$secure = 1

}

Else

{

$secure = 0

}

/ / check for SSL

$secure = ((REQ_PROTOCOL = 'https' AND $allowsecure)? True: false)

$name = $this- > _ config ['cookie_prefix']. $name

$filename = 'Ngamma A'

$linenum = 0

If (! headers_sent ($filename, $linenum))

{/ / consider showing an error message if there not sent using above variables?

If ($value = = "AND strlen ($this- > _ config ['cookiepath']) > 1 AND strpos ($this- > _ config [' cookiepath'],'/')! = = false)

{

/ / this will attempt to unset the cookie at each directory up the path.

/ / ie, cookiepath = / test/abc/. These will be unset: /, / test, / test/, / test/abc, / test/abc/

/ / This should hopefully prevent cookie conflicts when the cookie path is changed.

$dirarray = explode ('/', preg_replace ('# / + $#', ", $this- > _ config ['cookiepath']))

$alldirs = "

Foreach ($dirarray AS $thisdir)

{

$alldirs. = "$thisdir"

If (! empty ($thisdir))

{/ / try unsetting without the / at the end

Setcookie ($name, $value, $expire, $alldirs, $this- > _ config ['cookiedomain'], $secure)

}

Alldirs. = "/"

Setcookie ($name, $value, $expire, $alldirs, $this- > _ config ['cookiedomain'], $secure)

}

}

Else

{

Setcookie ($name, $value, $expire, $this- > _ config ['cookiepath'], $this- > _ config [' cookiedomain'], $secure)

}

}

Else if (! DEBUG)

{

Echo "can't set cookies"

}

}

Private function _ save ()

{

$cleaned = $this- > _ build_query_array ()

If ($this- > _ created)

{

/ / var_dump ($cleaned)

# insert query

$this- > _ mysqli- > query ('

INSERT IGNORE INTO'. $this- > _ config ['tablename']. '

('. Implode (',', array_keys ($cleaned)). ')

VALUES

('. Implode (',', $cleaned). ')

')

}

Else

{

# update query

$update = array ()

Foreach ($cleaned AS $key = > $value)

{

If (! empty ($this- > _ changes ["$key"]))

{

$update [] = "$key = $value"

}

}

If (sizeof ($update) > 0)

{

$sql = 'UPDATE'. $this- > _ config ['tablename']. '

SET'. Implode (',', $update). '

WHERE crc32sid ='. Sprintf ('% uplink, crc32 ($this- > _ dbsessionhash)). '

AND sessionhash =''. $this- > _ dbsessionhash. ''

/ / echo $sql

$this- > _ mysqli- > query ($sql)

}

}

}

Public function getOnlineUserNum ()

{

$sql ='

SELECT count (*) as cnt

FROM'. $this- > _ config ['tablename']. '

WHERE loggedin = 1

AND heartbeat >'. Date (TIMENOW-$this- > _ config ['cookie_timeout']). ''

$result = $this- > _ mysqli- > query ($sql)

$row = $result- > fetch_array (MYSQLI_ASSOC)

Return $row ['cnt']

}

Private function _ gc ()

{

$rand_num = rand (); # randow integer between 0 and getrandmax ()

If ($rand_num

< 100) { $sql = 'DELETE FROM ' . $this->

_ config ['tablename']. '

WHERE heartbeat

< '' . date('Y-m-d H:i:s' ,TIMENOW - $this->

_ config ['cookie_timeout']). ''

$this- > _ mysqli- > query ($sql)

}

}

Public function _ destruct ()

{

$this- > _ save ()

$this- > _ gc ()

$this- > _ mysqli- > close ()

}

}

On "how to achieve PHP independent Session database storage operation class" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, please share it out for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report