Why can’t I access php without logging in?
Sometimes some content on our website needs to be logged in to view. How to achieve this? , learn together.
1. The first is the login interface. After the user successfully logs in, set $_SESSION['islogin'] = true; to mark that the user has logged in.
login.php
<?php $username = $_POST['username']; $password = $_POST['password']; // 这里直接使用文本进行存储数据,推荐使用数据库 $user = file_get_contents('./user.txt'); //存放登录名和密码的文件 //user.txt 内容 admin 123456 //存放的格式可以随意改变 //根据登录名密码的存放格式获取用户名和密码 $user = explode(' ',$user); if($user[0] == $username && $user[1] == $password ){ //登录名和密码正确 设置session 并跳转 session_start(); //开启session $_SESSION['islogin'] = true; header("Location: index.php");exit; }else{ //登录名和密码错误 返回登录页 header("Location: login.php");exit; } ?>
2. Home page file, determine whether $_SESSION['islogin'] exists. If it does not exist, there will be no login. Jump to the login interface
index.php
<?php session_start(); //开启session //判断登录时的session是否存在 如果存在则表示已经登录 if(!$_SESSION['islogin']){ // !$_SESSION['islogin'] 表示不存在 回到登录页面 header("Location: login.php");exit; } //已经登录后的其他业务逻辑处理代码 ?>
3. This realizes functions that cannot be accessed without logging in.
For more PHP related knowledge, please visit PHP Chinese website!
The above is the detailed content of Why can't I access php without logging in?. For more information, please follow other related articles on the PHP Chinese website!