user7031 user7031 - 2 months ago 10
PHP Question

Do I need to check if sid exists in read callback function in session_set_save_handler?

Is it needed to check if sid existed, casue this callback generates $sid if there is no $sid exists, so what I want to ask is, is there a possiblity that the $sid will be empty?

function read($sid) { //Callback function in session_set_save_handler
if(empty($sid)) {
//do something
}
}

Answer

Do you mean the function is called by session_set_save_handler?

If so, there is no need to worry. You can see these examples below from two different sites. They both not worry it.

Example

function read($SessionKey){
     $sql = "SELECT uid FROM sessions WHERE session_id = '".$SessionKey."' limit 1"; 
     $query =$this->db->query($sql);
     if($row=$this->db->fetch_array($query)){
       return $row['uid'];
     }else{
         return ""; 
     }
} 

Another example from http://php.net/manual/zh/function.session-set-save-handler.php:

function read($sessID) { 
    // fetch session-data 
    $res = mysql_query("SELECT session_data AS d FROM ws_sessions 
                        WHERE session_id = '$sessID' 
                        AND session_expires > ".time(),$this->dbHandle); 
    // return data or an empty string at failure 
    if($row = mysql_fetch_assoc($res)) 
        return $row['d']; 
    return ""; 
}