In PHP, "session" refers to the session mechanism, which also refers to session. Then session in PHP is used to maintain relevant data when users continuously access web applications. This data can greatly improve the user experience and can definitely increase the attractiveness of your website.
In this article, I will combine a detailed example to give you a detailed introduction on how to use PHP to set up a successful login session.
→ Note: The idea of session control is to be able to track a user during a single session on the website.
The following are the specific steps to set up a session:
First we create a form that contains a text field named name and a submit button, and We set the method to post and the action to submit.php.
The form is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <form name="form" method="post" action="submit.php"> <label for="name">姓名:</label> <input type="text" name="name" id="name" /> <input type="submit" name="Submit" value="提交" /> </form> </body> </html>
Then create another page "submit.php" with the following code:
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2021/8/11 0011 * Time: 上午 11:32 */ // 发起会话 session_start(); // 检查表单是否已提交且名称不为空 if ($_POST && !empty($_POST['name'])) { // 设置会话变量 $_SESSION['name'] = $_POST['name']; } ?> <html> <head> <title>设置会话</title> </head> <body> <?php // 设置会话检查变量 if (isset($_SESSION['name'])) { // 如果设置了,用名字问候 echo '你好,'.$_SESSION['name'],"!"; echo '欢迎访问本页面!'; } else { // 如果没有设置,发送回登录 echo '请 <a href="form.php">登录</a>'; } ?> </body> </html>
The running effect of the above form code is:
If you enter the name "Xiao Wang" and click submit, the page effect will be:
If you do not enter any content, click submit directly. , it will be displayed as follows:
Finally, I would like to recommend "php session session (topic)", which will be introduced in more detail in this article If you know the session knowledge, interested friends can collect and learn~
The above is the detailed content of Use PHP to set up a successful login session (with code example). For more information, please follow other related articles on the PHP Chinese website!