Home >Backend Development >PHP Tutorial >Full session tutorial (3)_PHP tutorial
3. Session application examples
The following example snippets are for reference only. You can customize the session or not, as you like
(1) Used for user authentication
session_start();
$dbh=MySQL_connect("localhost:3306","xxxx","xxxx");
MySQL_select_db("znsoft");//Select database
$query="selectuseridfromreguserwhereuserid='$userid'andpass='$pass'";
//$userid$pass is the username and password passed by the login form
$res=MySQL_query($query,$dbh);
if($row=MySQL_fetch($res))
{
$reguser=$row[0];
?>
<script> <br>
alert("ok, buddy, welcome!"); <br>
</script>
}
else
{
$reguser="";
?>
<script> <br>
alert("sorry, you are not a registered user!"); <br>
</script>
//Put the code yourself
}
session_register("reguser");
?>
Check whether you are logged in on another page
================
session_start();
if(isset($reguser)&&$reguser!="")//Already logged in
{
echo "Welcome, buddy";
}
else//Not logged in
echo "Please register";
?>
Exit function
===============================
session_destroy();
//or $reguser="";
?>
(2) is used to pass variables
This program is used to transfer variables between pages
$name="m.y";
if(!session_is_registered("name"))//The session variable name is not registered
session_register("name");//Register variable name
?>
Second page
===================
echo$name;
//If you don’t want to use it anymore, delete it
if(session_is_registered("name"))//Whether to register, if already registered
session_unregister("name");//Delete it of course
?>