gpt4 book ai didi

php - 登录并绕过登录屏幕

转载 作者:行者123 更新时间:2023-11-29 11:32:06 25 4
gpt4 key购买 nike

所以我建立了我的第一个使用注册和登录的网站,它是使用 php 和 mysql 实现的。我的问题是,如果用户在通过登录页面后获得了他访问的页面的 URL,那么他当前可以将这些页面复制并粘贴到 URL 中并绕过登录。

问题:有什么方法可以确保实际登录已发生?

我的主机 000Webhost(免费)允许文件夹受密码保护,但我不知道如何或是否可以将其绑定(bind)到我的用户数据库中。

这是我就这个主题提出的第一个问题..请友善。

最佳答案

是的,有一些简单的方法可以检查用户是否登录,最好的方法是使用 $_SESSION超全局。当您使用 session 超全局时,您基本上是将有关特定用户的信息保存到服务器上,同时在用户计算机上保存一个 cookie,只要 session 有效(通常是 30 分钟),该 cookie 就可以唯一地标识该用户。用简单的英语来说,php 开发人员创建了一个 super 全局变量,它基本上使开发人员可以非常轻松地“维护状态”,而无需编写大量代码。

这就是使用 session 超全局的方式。在您网站的每个页面的顶部,您都会有这部分代码(甚至在 <!DOCTYPE html> 之上):

<?php session_start(); ?>

它的作用(以及许多其他功能)是在用户计算机上保存一个 cookie,在 session 有效时唯一地标识他。 NOW... 在用户登录后进入的页面上,您将看到类似以下的代码:

<?php

$username = $_POST['username'];//obtaining username from form
$password = $_POST['password'];//obtaining password from form
// i did not include any encryption code in this example
// so that the example is easier to understand, but keep in mind
// that encrypting your users passwords is super important

//for security reasons, I used prepared statements and binding parameters
//to compare the password and username obtained from the form with
//those in the database (in order to prevent sql injection):
$sql = "SELECT 1 FROM users WHERE username = :username AND password = :password LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();

if ($stmt->rowCount()>0)//if a row was found, then you know this user exists
{
//here I am saving information in the session super global that
//can be used to not only identify if a user is logged in on each
//page, but also to see which user is logged in, since often
//you want to give a user his own control panel or other features.
$_SESSION['authenticated'] = TRUE;
$_SESSION['username'] = htmlspecialchars($username);
}

?>

现在,在您拥有的每个页面上,您将包含以下代码:

<?php
if (isset($_SESSION['authenticated']))
{
echo "Hello there ".$_SESSION['username']."!<br>";
}
?>

前面的代码将回显类似“Hello there John!”的内容。如果用户名为 John。从这里,您可以在括号内包含您想要的任何代码,您只希望登录的用户可以看到因此,未登录的用户将无法查看网站的该部分,即使他们会看到网站 Logo ,以及 if 条件之外的所有其他内容。另外,前面的代码不必位于最顶部,只需 <?php session_start(); ?>需要这样做,这是因为 HTTP 协议(protocol)如何工作的原因。

如果这有帮助或者您有任何其他问题,请告诉我。

关于php - 登录并绕过登录屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37234634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com