2010-06-18 1 views
0

PHP와 MySQL을 사용하여 $ _SESSION에서 일부 데이터를 가져 오는 데 문제가 있습니다. 필자는 데이터베이스에 세션 정보를 저장하기 위해 "파일"을 사용하도록 서버에 알려주는 php.ini의 행을 주석 처리했습니다. 나는 데이터베이스에 정보를 쓰는 데 사용하는 클래스와 잘 작동한다. 사용자가 자격 증명을 전달하면 클래스가 인스턴스화되고 $ _SESSION 변수가 설정되고 사용자는 인덱스 페이지로 리디렉션됩니다. index.php 페이지에는 db 세션 클래스가있는 파일이 포함되어 있습니다. 인스턴스화시 session_start()를 호출하고 세션 변수가 $ _SESSION에 있어야하지만 var_dump ($ _ SESSION)을 수행하면 배열에 아무것도 없습니다. 그러나 mysql의 데이터를 보면 모든 세션 정보가 거기에있다. session_start()와 같은 동작은 호출되지 않았지만 클래스를 인스턴스화하여 작동합니다.PHP를 사용하여 mysql에 세션 데이터를 저장하면 테이블에서 데이터를 제대로 검색하지 못합니다.

어떤 생각이 잘못되었을 수 있습니까?

<?php 

    include_once "classes/phpsessions_db/class.dbsession.php"; //used for sessions 
    var_dump($_SESSION); 
?> 
<html> 
. 
. 
. 
</html> 

가 여기에 dbsession 클래스의 : 당신은하지만 아무데도, 삽입에 SESSION_ID를 직렬화하고

<?php 

error_reporting(E_ALL); 

class dbSession 
{ 

    function dbSession($gc_maxlifetime = "", $gc_probability = "", $gc_divisor = "") 
    { 
     // if $gc_maxlifetime is specified and is an integer number 
     if ($gc_maxlifetime != "" && is_integer($gc_maxlifetime)) { 

      // set the new value 
      @ini_set('session.gc_maxlifetime', $gc_maxlifetime); 

     } 

     // if $gc_probability is specified and is an integer number 
     if ($gc_probability != "" && is_integer($gc_probability)) { 

      // set the new value 
      @ini_set('session.gc_probability', $gc_probability); 

     } 

     // if $gc_divisor is specified and is an integer number 
     if ($gc_divisor != "" && is_integer($gc_divisor)) { 

      // set the new value 
      @ini_set('session.gc_divisor', $gc_divisor); 

     } 

     // get session lifetime 
     $this->sessionLifetime = ini_get("session.gc_maxlifetime"); 

     //Added by AARON. cancel the session's auto start,important, without this the session var's don't show up on next pg. 
     session_write_close(); 

     // register the new handler 
     session_set_save_handler(
      array(&$this, 'open'), 
      array(&$this, 'close'), 
      array(&$this, 'read'), 
      array(&$this, 'write'), 
      array(&$this, 'destroy'), 
      array(&$this, 'gc') 
     ); 

     register_shutdown_function('session_write_close'); 

     // start the session 
     @session_start(); 
    } 

    function stop() 
    {  
     $new_sess_id = $this->regenerate_id(true); 
     session_unset(); 
     session_destroy(); 

     return $new_sess_id; 
    } 

    function regenerate_id($return_val=false) 
    { 
     // saves the old session's id 
     $oldSessionID = session_id(); 
     // regenerates the id 
     // this function will create a new session, with a new id and containing the data from the old session 
     // but will not delete the old session 
     session_regenerate_id(); 

     // because the session_regenerate_id() function does not delete the old session, 
     // we have to delete it manually 
     //$this->destroy($oldSessionID); 

     //ADDED by aaron 
     // returns the new session id 
     if($return_val) 
     { 
      return session_id(); 
     } 
    } 

    function open($save_path, $session_name) 
    { 
     // global $gf; 
     // $gf->debug_this($gf, "GF: Opening Session"); 
     // change the next values to match the setting of your mySQL database 
     $mySQLHost = "localhost"; 
     $mySQLUsername = "user"; 
     $mySQLPassword = "pass"; 
     $mySQLDatabase = "sessions"; 

     $link = mysql_connect($mySQLHost, $mySQLUsername, $mySQLPassword); 

     if (!$link) { 

      die ("Could not connect to database!"); 

     } 

     $dbc = mysql_select_db($mySQLDatabase, $link); 

     if (!$dbc) { 

      die ("Could not select database!"); 

     } 

     return true; 

    } 

    function close() 
    { 
     mysql_close(); 
     return true; 
    } 

    function read($session_id) 
    { 

     $result = @mysql_query(" 
      SELECT 
       session_data 
      FROM 
       session_data 
      WHERE 
       session_id = '".$session_id."' AND 
       http_user_agent = '".$_SERVER["HTTP_USER_AGENT"]."' AND 
       session_expire > '".time()."' 
     "); 

     // if anything was found 

     if (is_resource($result) && @mysql_num_rows($result) > 0) { 

      // return found data 
      $fields = @mysql_fetch_assoc($result); 
      // don't bother with the unserialization - PHP handles this automatically 
      return unserialize($fields["session_data"]); 

     } 

     // if there was an error return an empty string - this HAS to be an empty string 
     return ""; 

    } 

    function write($session_id, $session_data) 
    { 
     // global $gf; 

     // first checks if there is a session with this id 
     $result = @mysql_query(" 
      SELECT 
       * 
      FROM 
       session_data 
      WHERE 
       session_id = '".$session_id."' 
     "); 

     // if there is 
     if (@mysql_num_rows($result) > 0) 
     { 
      // update the existing session's data 
      // and set new expiry time 
      $result = @mysql_query(" 
       UPDATE 
        session_data 
       SET 
        session_data = '".serialize($session_data)."', 
        session_expire = '".(time() + $this->sessionLifetime)."' 
       WHERE 
        session_id = '".$session_id."' 
      "); 

      // if anything happened 
      if (@mysql_affected_rows()) 
      { 
       // return true 
       return true; 
      } 


     } 
     else // if this session id is not in the database 
     { 
      // $gf->debug_this($gf, "inside dbSession, trying to write to db because session id was NOT in db"); 
      $sql = " 
       INSERT INTO 
        session_data 
         (
          session_id, 
          http_user_agent, 
          session_data, 
          session_expire 
         ) 
        VALUES 
         (
          '".serialize($session_id)."', 
          '".$_SERVER["HTTP_USER_AGENT"]."', 
          '".$session_data."', 
          '".(time() + $this->sessionLifetime)."' 
         ) 
      "; 

      // insert a new record 
      $result = @mysql_query($sql); 

      // if anything happened 
      if (@mysql_affected_rows()) 
      { 
       // return an empty string 
       return ""; 
      } 

     } 

     // if something went wrong, return false 
     return false; 

    } 

    function destroy($session_id) 
    { 

     // deletes the current session id from the database 
     $result = @mysql_query(" 
      DELETE FROM 
       session_data 
      WHERE 
       session_id = '".$session_id."' 
     "); 

     // if anything happened 
     if (@mysql_affected_rows()) { 

      // return true 
      return true; 

     } 

     // if something went wrong, return false 
     return false; 

    } 

    function gc($maxlifetime) 
    { 

     // it deletes expired sessions from database 
     $result = @mysql_query(" 
      DELETE FROM 
       session_data 
      WHERE 
       session_expire < '".(time() - $maxlifetime)."' 
     "); 

    } 

} //End of Class 

    $session = new dbsession(); 

?> 

답변

1

오류보고가 올바르게 작동하면 작동하지 않는 이유가 의심 스럽습니다.

세션 데이터를 이스케이프 처리하고 있지 않으므로 ID를 serialize하지 않아야합니다. 우연히도 코드가 복잡하고 문서화가 잘되지 않아 비효율적입니다. (!) : 이미 데이터가있는 경우 다음 삽입 또는 업데이트 할 선택을 참조 할 필요가 없습니다 귀하의 코멘트처럼

$sql = "REPLACE INTO 
       session_data 
        (
         session_id, 
         http_user_agent, 
         session_data, 
         session_expire 
        ) 
       VALUES 
        (
         '".mysql_real_escape_string($session_id))."', 
         '".mysql_real_escape_string($_SERVER["HTTP_USER_AGENT"])."', 
         '".mysql_real_escape_string($session_data)."', 
         '".(time() + $this->sessionLifetime)."' 
        ) 

하고 ....

// don't bother with the unserialization - PHP handles this automatically 
     return unserialize($fields["session_data"]); 

은 말한다 - 돈 ' 처리기의 데이터를 직렬화 해제하려고하지 마십시오.

C.

+1

고마워, 나는이 수업을 phpclasses.org에서 찾아 내 사용을 위해 수정했다. 한 달 전에 뭔가 다른 것을 시도 할 때 거기에 그 unserialize()를 남겨 놓은 것을 알았습니다 ... 나는 그 테이블 위에 프로젝트 테이블을 올려 놓았습니다. 일단 내가 그것을 제거하고 직렬화 된 것들을 제거했습니다. 당신이 옳았 기 때문에 신용은 당신에게 간다. 나는 당신의 코드로 바꾸기를 더 좋아한다. 당신의 도움을 주셔서 감사합니다! – Ronedog

0

다음은 HTML입니다. 그걸 바꾸어보세요 ...

+0

덕분에, 나는 모든은 $ SESSION_ID이 사용 된 장소, 즉 직렬화 ($ SESSION_ID)를 직렬화,하지만 같은 결과를 얻을. 다른 아이디어? – Ronedog

관련 문제