PHP custom session save path and delete, logout and write methods

The example of this article describes the method of customizing the session saving path in PHP and deleting, logging out and writing. Share it with everyone for your reference. The specific method is as follows:

$sessionpath=session_save_path(); //Get the save path of the current session
echo $sessionpath;
if(strpos($sessionpath,";")!==false) //If there is a semicolon in the path
{
  $sessionpath=substr($sessionpath,strpos($sessionpath,";")+1); //Set new path
}
function open($save_path,$session_name) //Define the open function
{
  global $sess_save_path,$sess_session_name; //Predefined session path and name
  $sess_save_path=$save_path; //Define the save path
  $sess_session_name=$session_name; //Define the session name
  return(true); //return true value
}
function close() //Define the close function
{
  return(true); //Return the true value directly
}
function read($id) //Define the read function
{
  global $sess_save_path,$sess_session_name; //Predefined save path and name
  $sess_file="$sess_save_path/sess_$id"; //Define file
  if($fp=@fopen($sess_file,"r")) //Open the file
  {
    $sess_data=fread($fp,filesize($sess_file)); //Read file
    return($sess_data); //return the read content
  }
  else
  {
    return(""); //If the read fails, it must return a null value
  }
}
function write($id,$sess_data) //Define write function
{
  global $sess_save_path,$sess_session_name; //Predefined save path and name
  $sess_file="$sess_save_path/sess_$id"; //Define file
  if($fp=@fopen($sess_file,"w")) //Open the file
  {
    return(fwrite($fp,$sess_data)); //Execute write operation
  }
  else
  {
   return(false); //If the opening fails, return an error
  }
}
function destroy($id) //Define the logout function
{
  global $sess_save_path,$sess_session_name;
  $sess_file="$sess_save_path/sess_$id"; //Specify the file
  return(@unlink($sess_file)); //delete session file
}
function gc($maxlifetime) //Define expiration function
{
  return true; //Return the true value directly
}
session_set_save_handler("open","close","read","write","destroy","gc"); //设置函数
session_start(); //Initialize session
//The following can continue to use the session normally

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325636351&siteId=291194637