Home >Backend Development >PHP Problem >Why can't I access php without logging in?

Why can't I access php without logging in?

angryTom
angryTomOriginal
2019-10-28 14:50:063796browse

Why can't I access php without logging in?

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[&#39;username&#39;];
    $password = $_POST[&#39;password&#39;];
    // 这里直接使用文本进行存储数据,推荐使用数据库
    $user = file_get_contents(&#39;./user.txt&#39;); //存放登录名和密码的文件  
    //user.txt 内容 admin 123456   //存放的格式可以随意改变
    //根据登录名密码的存放格式获取用户名和密码
    $user = explode(&#39; &#39;,$user);
    if($user[0] == $username && $user[1] == $password ){
        //登录名和密码正确 设置session 并跳转
        session_start(); //开启session
        $_SESSION[&#39;islogin&#39;] = 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[&#39;islogin&#39;]){
        // !$_SESSION[&#39;islogin&#39;]  表示不存在 回到登录页面
        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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn