2017-02-20 33 views
0

我正在使用PHP會話處理程序在我的網站上實現持久會話。 問題是,在某些時候,我需要將user_key插入到另一個MySQL表中,我不知道如何從代碼中檢索該信息。如何從PHP持久會話處理程序中檢索特定信息?

例如,數據行到我的會話表:

active|i:1487613760;user_username|s:20:"[email protected]";user_key|s:8:"a5186adc";authenticated|b:1;user_name|s:12:"victor";user_email|s:20:"[email protected]";remember|b:1; 

,我想知道是否有一個簡單的方法來獲得user_key變量。

對不起,如果有點混淆。

+0

,似乎一個奇怪的序列化格式,如何您的會話處理程序序列化呢? – DevDonkey

回答

0

第一個選項是反序列化這個字符串。 http://php.net/manual/en/function.unserialize.php

第二個選項,您可以使用的preg_match功能與下一模式:

preg_match('/user_key\|s:\d+:"([a-zA-Z0-9]+)"/', $string, $match); 
+0

感謝您的幫助4EACH。 問題是,我不知道如何獲得這個特定的行,一旦同時會有很多會話。 –

+0

你對用戶的唯一性信息是什麼? – 4EACH

+0

我需要user_key,以便我可以插入到另一個mysql表。 有一種方法「閱讀」閱讀與處理程序的信息... –

0

我不能在任何地方找到的東西來處理序列化的字符串,它不是我見過的該格式。

然而,繼承人快速功能,把它變成一個數組(它可能不是太優雅,但我只有1種咖啡):

$string = 'active|i:1487613760;user_username|s:20:"[email protected]";user_key|s:8:"a5186adc";authenticated|b:1;user_name|s:12:"victor";user_email|s:20:"[email protected]";remember|b:1; 
'; 

$array = deserializeSessionString($string); 

echo $array['user_key']; 

// deserialize a session string into an array 
function deserializeSessionString($string) 
{ 
    $output = []; 
    // separate the key-value pairs and iterate 
    foreach(explode(';', $string) as $p) { 
     // separate the identifier with the contents 
     $bits = explode('|', $p); 

     // conditionally store in the correct format. 
     if(isset($bits[1])) { 
      $test = explode(':', $bits[1]); 
      switch($test[0]) { 
       // int 
       case 'i': 
        $output[$bits[0]] = $test[1]; 
        break; 
       case 's': 

        // string 
        // ignore test[1], we dont care about it 
        $output[$bits[0]] = $test[2]; 
        break; 

       case 'b': 
        // boolean 
        $output[$bits[0]] = ($test[1] == 1 ? true : false); 
        break; 
      } 
     } 

    } 

    return $output; 
} 

,那麼你應該能夠訪問你需要只用鑰匙:

echo $array['user_key']; 

heres an example

+0

感謝您的回覆DevMonkey ... 它可能會幫助,如果我可以得到會話ID或某些「索引」的特定行。 我不知道如果會話處理程序可以幫助我與代碼本身,但在此期間,我正在設置和獲取_SESSION變量上的每個頁面上的user_key ... 再次謝謝。 –

相關問題