Password protect a page without db access with php

▼魔方 西西 提交于 2020-01-13 05:54:34

问题


Is it possible to password protect a page without db access? I may have only few pages. But I should be able to change password and also save sessions etc. And I want a secure way as it's for production site!

How is it to store in a config.php after md5:

 <?php
 username="admin"; 
 password="1a1dc91c907325c69271ddf0c944bc72";
 ?>

If this is a good idea, is there a way to restrict access to this php from only one script called check.php or something?


回答1:


Sure, why not? You can use flat files in inaccessible directory (protected by .htaccess or out of the www root) and use that as a database.

Here's a simple login class I've whipped up:

class SimpleLogin {

    private $users;
    private $db = './pass.txt';

    function __construct() {
        $data = file_get_contents($this->db);

        if (!$data) {
           die('Can\'t open db');
        } else {
            $this->users = unserialize($data);
        }
    }

    function save() {
        if (file_put_contents($this->db, serialize($this->users)) === false)
            die('Couldn\'t save data');
    }

    function authenticate($user, $password) {
        return $this->users[$user] == $this->hash($password);
    }

    function addUser($user, $password) {
        $this->users[$user] = $this->hash($password);
        $this->save();
    }

    function removeUser($user) {
        unset($this->users[$user]);
        $this->save();
    }

    function userExists($user) {
        return array_key_exists($user, $this->users);
    }

    function userList() {
        return array_keys($this->users);
    }

    // you can change the hash function and salt here
    function hash($password) {
        $salt = 'jafo2ijr02jfsau02!)U(jf';
        return sha1($password . $salt);
    }

}

NOTE: You really should turn off error reporting if you are going to use this in an actual server. This can be done by calling error_reporting() or by adding '@' in front of file_get_contents and file_put_contents (ie: so it turns into @file_get_contents)

Usage example: http://left4churr.com/login/




回答2:


You should use .htaccess to do that. You also can protect by .htaccess your sensible php files, with something like :

Order Allow,Deny
Deny from All



回答3:


You could use HTTP authentication with PHP. Very good examples present in PHP-docu.




回答4:


Actually a database have nothing to do with password protection.
you can write login and password directly in your script as well as keeping in in the database.

There is no need in restricting access to your php file. Being called over HTTP, it will be just blank page and nothing more.

So, it's all right to store it that way.
Quite enough for the site that even don't use a database.



来源:https://stackoverflow.com/questions/3402782/password-protect-a-page-without-db-access-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!