php 无需数据库的简单登录脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1381205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:17:33  来源:igfitidea点击:

Easy login script without database

phplogin

提问by Sampson

How do I create an easy login script that does not require a database. I would like it to be safe.

如何创建不需要数据库的简单登录脚本。我希望它是安全的。

Alright, what about this script, i just made it by my knowledge in php.

好吧,这个脚本怎么样,我只是根据我在 php 方面的知识制作的。

<?php 
// Start session
session_start(); 

// Username and password
$ID = "admin";
$pass = "123456";

if (isset($_POST["ID"]) && isset($_POST["pass"])) { 

    if ($_POST["ID"] === $anvandarID && $_POST["pass"] === $pass) { 
    /
    $_SESSION["inloggedin"] = true; 

    header("Location: safe_site.php"); 
    exit; 
    } 
        // Wrong login - message
        else {$wrong = "Bad ID and password, the system could not log you in";} 
}
?> 

The safe_site.php contains this and some content:

safe_site.php 包含以下内容和一些内容:

session_start();

if (!isset($_SESSION["inloggning"]) || $_SESSION["inloggning"] !== true) {
header("Location: login.php");
exit;
}

回答by Mark Biek

It's not an ideal solution but here's a quick and dirty example that shows how you could store login info in the PHP code:

这不是一个理想的解决方案,但这里有一个快速而肮脏的例子,展示了如何在 PHP 代码中存储登录信息:

<?php
session_start();

$userinfo = array(
                'user1'=>'password1',
                'user2'=>'password2'
                );

if(isset($_GET['logout'])) {
    $_SESSION['username'] = '';
    header('Location:  ' . $_SERVER['PHP_SELF']);
}

if(isset($_POST['username'])) {
    if($userinfo[$_POST['username']] == $_POST['password']) {
        $_SESSION['username'] = $_POST['username'];
    }else {
        //Invalid Login
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Login</title>
    </head>
    <body>
        <?php if($_SESSION['username']): ?>
            <p>You are logged in as <?=$_SESSION['username']?></p>
            <p><a href="?logout=1">Logout</a></p>
        <?php endif; ?>
        <form name="login" action="" method="post">
            Username:  <input type="text" name="username" value="" /><br />
            Password:  <input type="password" name="password" value="" /><br />
            <input type="submit" name="submit" value="Submit" />
        </form>
    </body>
</html>

回答by Sampson

FacebookConnector OpenIDare two great options.

FacebookConnectOpenID是两个不错的选择。

Basically, your users login to other sites they are already members of (Facebook, or Google), and then you get confirmation from that site telling you the user is trustworthy - start a session, and they're logged in. No database needed (unless you want to associate more data to their account).

基本上,您的用户登录到他们已经是其成员的其他站点(Facebook 或 Google),然后您从该站点获得确认,告诉您该用户是值得信赖的 - 启动会话,然后他们已登录。不需要数据库(除非您想将更多数据关联到他们的帐户)。

回答by Andres

I would use a two file setup like this:

我会使用这样的两个文件设置:

index.php

索引.php

<?php 
session_start(); 

define('DS',  TRUE); // used to protect includes
define('USERNAME', $_SESSION['username']);
define('SELF',  $_SERVER['PHP_SELF'] );

if (!USERNAME or isset($_GET['logout']))
 include('login.php');

// everything below will show after correct login 
?>

login.php

登录.php

<?php defined('DS') OR die('No direct access allowed.');

$users = array(
 "user" => "userpass"
);

if(isset($_GET['logout'])) {
    $_SESSION['username'] = '';
    header('Location:  ' . $_SERVER['PHP_SELF']);
}

if(isset($_POST['username'])) {
    if($users[$_POST['username']] !== NULL && $users[$_POST['username']] == $_POST['password']) {
  $_SESSION['username'] = $_POST['username'];
  header('Location:  ' . $_SERVER['PHP_SELF']);
    }else {
        //invalid login
  echo "<p>error logging in</p>";
    }
}

echo '<form method="post" action="'.SELF.'">
  <h2>Login</h2>
  <p><label for="username">Username</label> <input type="text" id="username" name="username" value="" /></p>
  <p><label for="password">Password</label> <input type="password" id="password" name="password" value="" /></p>
  <p><input type="submit" name="submit" value="Login" class="button"/></p>
  </form>';
exit; 
?>

回答by Tom Pa?ourek

Save the username and password hashes in array in a php file instead of db.

将数组中的用户名和密码哈希保存在 php 文件而不是 db 中。

When you need to authenticate the user, compute hashes of his credentials and then compare them to hashes in array.

当您需要对用户进行身份验证时,计算其凭据的哈希值,然后将它们与数组中的哈希值进行比较。

If you use safe hash function (see hash function and hash algosin PHP documentation), it should be pretty safe (you may consider using salted hash) and also add some protections to the form itself.

如果您使用安全散列函数(请参阅PHP 文档中的散列函数和散列算法),它应该非常安全(您可以考虑使用加盐散列)并且还为表单本身添加了一些保护。

回答by dnagirl

If you don't have a database, where will the PERMANENT record of your users' login data be stored? Sure, while the user is logged in, the minimal user information required for your site to work can be stored in a session or cookie. But after they log out, then what? The session goes away, the cookie can be hacked.

如果您没有数据库,您的用户登录数据的永久记录将存储在哪里?当然,当用户登录时,您的站点工作所需的最少用户信息可以存储在会话或 cookie 中。但是当他们退出后,然后呢?会话消失,cookie 可以被黑客入侵。

So your user comes back to your site. He tries to log in. What trustworthy thing does your site compare his login info to?

所以你的用户会回到你的网站。他试图登录。你的网站将他的登录信息与哪些值得信赖的东西进行比较?

回答by Andrew Seward

***LOGIN script that doesnt link to a database or external file. Good for a global password -

***登录脚本不链接到数据库或外部文件。适合全局密码 -

Place on Login form page - place this at the top of the login page - above everything else***

放置在登录表单页面上 - 将其放在登录页面的顶部 - 高于其他一切***

<?php

if(isset($_POST['Login'])){

if(strtolower($_POST["username"])=="ChangeThis" && $_POST["password"]=="ChangeThis"){
session_start();
$_SESSION['logged_in'] = TRUE;
header("Location: ./YourPageAfterLogin.php");

}else {
$error= "Login failed !";
}
}
//print"version3<br>";
//print"username=".$_POST["username"]."<br>";
//print"password=".$_POST["username"];
?>

*Login on following pages - Place this at the top of every page that needs to be protected by login. this checks the session and if a user name and password has *

*在以下页面登录 - 将其放置在需要登录保护的每个页面的顶部。这将检查会话以及用户名和密码是否具有 *

<?php
session_start();
if(!isset($_SESSION['logged_in']) OR $_SESSION['logged_in'] != TRUE){

header("Location: ./YourLoginPage.php");
}
?>

回答by Frank Slezak

Try this:

尝试这个:

<?php
        session_start();
        $userinfo = array(
            'user'=>'5d41402abc4b2a76b9719d911017c592', //Hello...
        );

        if(isset($_GET['logout'])) {
            $_SESSION['username'] = '';
            header('Location:  ' . $_SERVER['PHP_SELF']);
        }

        if(isset($_POST['username'])) {
            if($userinfo[$_POST['username']] == md5($_POST['password'])) {
                $_SESSION['username'] = $_POST['username'];
            }else {
                header("location:403.html"); //replace with 403
            }
        }
?>
<?php if($_SESSION['username']): ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <title>Logged In</title>
        </head>

        <body>
            <p>You're logged in.</p>
            <a href="logout.php">LOG OUT</a>
        </body>
    </html>

<?php else: ?>
    <html>
        <head>
            <title>Log In</title>
        </head>
        <body>
            <h1>Login needed</h1>
            <form name="login" action="" method="post">
                <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
                    <tr>
                        <td colspan="3"><strong>System Login</strong></td>
                    </tr>
                    <tr>
                        <td width="78">Username:</td>
                        <td width="294"><input name="username" type="text" id="username"></td>
                    </tr>
                    <tr>
                        <td>Password:</td>
                        <td><input name="password" type="password" id="password"></td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td><input type="submit" name="Submit" value="Login"></td>
                    </tr>
                </table>
            </form>
        </body>
    </html>
<?php endif; ?>

You will need a logout, something like this (logout.php):

你需要一个注销,像这样(logout.php):

<?php
    session_start();
    session_destroy();
    header("location:index.html"); //Replace with Logged Out page. Remove if you want to use HTML in same file.
?>

// Below is not needed, unless header above is missing. In that case, put logged out text here.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
    </head>
    <body>
        <!-- Put logged out message here -->
    </body>
</html>

回答by Ken Keenan

You can do the access control at the Web server level using HTTP Basic authentication and htpasswd. There are a number of problems with this:

您可以使用 HTTP 基本身份验证和htpasswd在 Web 服务器级别进行访问控制。这有很多问题:

  1. It's not very secure (username and password are trivially encoded on the wire)
  2. It's difficult to maintain (you have to log into the server to add or remove users)
  3. You have no control over the login dialog box presented by the browser
  4. There is no way of logging out, short of restarting the browser.
  1. 它不是很安全(用户名和密码在线路上被简单地编码)
  2. 维护困难(添加或删除用户需要登录服务器)
  3. 您无法控制浏览器显示的登录对话框
  4. 除了重新启动浏览器之外,没有办法注销。

Unless you're building a site for internal use with few users, I wouldn't really recommend it.

除非您正在构建一个用户很少的内部使用站点,否则我不会真正推荐它。

回答by mkoryak

if you dont have a database, you will have to hardcode the login details in your code, or read it from a flat file on disk.

如果您没有数据库,则必须在代码中对登录详细信息进行硬编码,或者从磁盘上的平面文件中读取它。

回答by Helen Neely

There's no reason for not using database for login implementation, the very least you can do is to download and install SQLite if your hosting company does not provide you with enough DB.

没有理由不使用数据库进行登录,如果您的托管公司没有为您提供足够的数据库,您至少可以下载并安装 SQLite。