This article mainly introduces to you the specific implementation method of PHP using session to determine whether the user is logged in.
Introduction to relevant knowledge about session in PHP, in the previous article [How to store and delete variables in session in PHP? 】【How does PHP use session to record user login information? ], we have introduced the related usage of session to you. Friends who need it can choose to refer to it first.
Let’s combine it with [How does PHP use session to record user login information? ] The example in this article introduces how to use session to determine whether the user is logged in .
Session code example to determine whether the user is logged in:
index.php
<?php echo "<h1>这里是主页</h1>"; session_start(); $name = $_SESSION['username']; if ($name) { echo "<script> alert(\"尊敬的$name ,欢迎回来!!\"); </script>"; }else{ echo "<script> alert('您还尚未登录!请返回登录~~') </script>"; echo "<a href='login.html'>如果跳转失败请点击跳转~~</a>"; header("Refresh:1;url=login.html"); }
Here we first The username in the session is assigned to a variable $name, and then an if statement is used to determine whether the $name is empty. If it is already logged in, it will prompt something like "Dear $name, welcome back!!\". If it is empty, a pop-up will appear. A prompt box will prompt you to log in and jump back to the login.html interface.
Then we access through the browser and test:
Enter the username and password
Click to log in, after successful login The page is as follows:
At this time, the user’s login information has been saved in our session. If we close the window, Reopening a new window will log you in directly.
If we close the browser and then open the main page, the following prompt message will pop up:
This It's because when we close the browser, the session value is automatically deleted.
This article is about the specific method of judging whether the user is logged in by session in PHP. It has certain reference value. I hope it will be helpful to friends in need!
If you want to learn more about PHP, you can follow the PHP Chinese website PHP Video Tutorial, everyone is welcome to refer to and learn!
Related topic recommendations: php session (including pictures, texts, videos, cases)
The above is the detailed content of How does PHP use session to determine whether the user is logged in? (Pictures + Videos). For more information, please follow other related articles on the PHP Chinese website!