PHP , MYSQL 登录后才显示网站

标签 php mysql authentication

我正在尝试创建一个您需要登录才能访问页面的网站。一切正常,但我想阻止直接访问。

登录服务器.php :

<?php
$error=''; //Variable to Store error message;
if(isset($_POST['submit'])){
    if(empty($_POST['user']) || empty($_POST['pass'])){
        $error = "Username or Password is Invalid";
    }
    else
    {
        //Define $user and $pass
        $user=$_POST['user'];
        $pass=$_POST['pass'];
        //Establishing Connection with server by passing server_name, user_id and pass as a patameter
        $conn = mysqli_connect("localhost", "root", "");
        //Selecting Database
        $db = mysqli_select_db($conn, "test");
        //sql query to fetch information of registerd user and finds user match.
        $query = mysqli_query($conn, "SELECT * FROM userpass WHERE pass='$pass' AND user='$user'");

        $rows = mysqli_num_rows($query);
        if($rows == 1){
            header("Location: welcome.php"); // Redirecting to other page
        }
        else
        {
            $error = "Username of Password is Invalid";
        }
        mysqli_close($conn); // Closing connection
    }
}

?>

欢迎.php

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Welcome</h1>
</body>
</html>

最佳答案

In loginserver.php page you have to start session at top of page.

<?php
session_start();
include('conn.php');

//  rest of code...

    $row = mysql_fetch_array($query);
if($rows == 1){
    $_SESSION['uname'] = $row['user'];

            header("Location: welcome.php"); // Redirecting to other page
        }
?>  

after that check it in welcome.php page check session variable coming from user login page is active or not.    

<?php
session_start();
include('conn.php');

if(!isset($_SESSION['uname'])){
 header("Location:loginserver.php");    
}
?>

希望对你有用。

关于PHP , MYSQL 登录后才显示网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50377297/

相关文章:

java - 通过HQL从两个表中获取数据并插入到一个表中

php - 有没有办法在删除行之前检查 MySql 中的约束违规情况?

PHP 7.4 和 MySQL : caching_sha2_password Denying long (20c) passwords

php - 在 PHP 中从一个位置建立连接

php - 评级与 2 种形式冲突

php - 图片发布和 mysql BLOB 变量出现问题

php - 使用散列检查具有 $_POST 值的页面是否已刷新

python - 如何返回 .fetchone() 返回的元组中的单个元素?

http - 使用 HTTPS 时 OAuth 是否无关紧要?

forms - .htaccess 重写阻止登录