0

我想用 PHP 和Glue 框架创建一个简单的登录系统。我的代码是这样的:

glue("route")->post("/login", function($params) {
    // I'm trying to catch the variable first
    echo $params['user'] .'aaand'. $params['pass'];
});

形式是:

<form action="/login" method="POST">
    <input type="text" name="user">
    <input type="password" name="pass">
</form>

问题是,我怎样才能捕获这两个变量 -user然后pass将其插入 PHP Sessions ?

感谢您的回答和解释!

4

1 回答 1

0

带有(Captcha,CSRF)保护的示例登录/注销代码

我会跟你说实话,我和你一样喜欢小脚印。^_^

如果您想了解事物的工作原理并开始构建安全且简单的东西,那没关系。

测试任何来到这个世界的东西并试图打破它,直到你做出一些不可能被破解的东西。;)

首先:在您的 Web 服务器的根目录中创建一个文件夹并将其命名为“ glue ”。

在该文件夹中,使这些文件具有以下内容:

.htaccess

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

RewriteEngine On

# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

胶水.php

<?php
/**
* glue
*
* Provides an easy way to map URLs to classes. URLs can be literal
* strings or regular expressions.
*
* When the URLs are processed:
*      * delimiter (/) are automatically escaped: (\/)
*      * The beginning and end are anchored (^ $)
*      * An optional end slash is added (/?)
*       * The i option is added for case-insensitive searches
*
* Example:
*
* $urls = array(
*     '/' => 'index',
*     '/page/(\d+)' => 'page'
* );
*
* class page {
*      function GET($matches) {
*          echo "Your requested page " . $matches[1];
*      }
* }
*
* glue::stick($urls);
*
*/
class glue {
    /**
     * stick
     *
     * the main static function of the glue class.
     *
     * @param   array       $urls       The regex-based url to class mapping
     * @throws  Exception               Thrown if corresponding class is not found
     * @throws  Exception               Thrown if no match is found
     * @throws  BadMethodCallException  Thrown if a corresponding GET,POST is not found
     *
     */
    static function stick ($urls) {
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        $path = $_SERVER['REQUEST_URI'];
        $found = false;
        krsort($urls);
        foreach ($urls as $regex => $class) {
            $regex = str_replace('/', '\/', $regex);
            $regex = '^' . $regex . '\/?$';
            if (preg_match("/$regex/i", $path, $matches)) {
                $found = true;
                if (class_exists($class)) {
                    $obj = new $class;
                    if (method_exists($obj, $method)) {
                        $obj->$method($matches);
                    } else {
                        throw new BadMethodCallException("Method, $method, not supported.");
                    }
                } else {
                    throw new Exception("Class, $class, not found.");
                }
                break;
            }
        }
        if (!$found) {
            throw new Exception("URL, $path, not found.");
        }
    }
}

索引.php

<?
/*
* This Login needs following things to make it secure:
* - HTTPS (Run login page on Encrypted Connection)
* - Protection against SQL-Injection
*/

session_start();

require_once("glue.php");

$urls = array(
    '/glue/' => 'index',
    '/glue/logout' => 'logout',
    '/glue/captcha' => 'captcha',
);

class index {

    function GET() {

        if(isset($_SESSION['is_logged'])){

            echo "<h1>Hello Again, {$_SESSION['name']}!</h1>";

            echo "<a href='/glue/logout'>Log Me Out!</a>";

        }else{

            $csrf = sha1(uniqid(time()));

            $_SESSION['csrf'] = $csrf;

            $form = " 
            <h1>Quick Login not Secure (needs HTTPS)</h1>
            <hr/>
            <form METHOD='POST'>
                <input type='hidden' name='csrf' value='$csrf'/>
                <label>User Name:</label><input type='text' name='username'/> <br/>
                <label>Password:</label><input type='password' name='pwd'/> <br/>
                <img src='/glue/captcha'/><br/>
                <label>Captcha:</label><input type='text' name='captcha'/> <br/>
                <input type='submit' name='Login' value='Login me in !'/>
            </form>
            ";

            echo $form;
        }
    }

    function POST(){

        if($_POST['username'] === 'test' && $_POST['pwd'] === 'test' && $_SESSION['captcha'] == $_POST['captcha'] && $_SESSION['csrf'] === $_POST['csrf']){

            echo "<h1>Salam {$_POST['username']}, You have logged Successfully...</h1>";

            echo "<a href='/glue'><h4>Goto Your page now</h4></a>";

            $_SESSION['is_logged'] = True;
            $_SESSION['name'] = $_POST['username'];

        }else{

            echo "<h1>Failed to login, <a href='/glue'>try again</a></h1>";
        }
    }
}

class logout{

    function GET(){

        session_destroy();

        header('location: /glue');
    }
}

/* it does generate captcha and save it to session on the fly */
class captcha{

    function generatePassword($length = 5) {

        $code = rand(1000, 9999);

        $possibleChars = "ABCDEFGHJKLMNPQRSTUVWXYZ" . $code;
        $password = '';

        for($i = 0; $i < $length; $i++) {
            $rand = rand(0, strlen($possibleChars) - 1);
            $password .= substr($possibleChars, $rand, 1);
        }

        return str_shuffle($password);
    }

    function GET(){

        $code = $this->generatePassword();

        $_SESSION["captcha"] = $code;
        $im = imagecreatetruecolor(260, 24);
        $bg = imagecolorallocate($im, 0, 0, 0); //background color blue
        $fg = imagecolorallocate($im, 255, 255, 255);//text color white
        imagefill($im, 0, 0, $bg);
        imagestring($im, 5, 100, 5,  $code, $fg);
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-type: image/png');
        imagepng($im);
        imagedestroy($im);
    }
}

glue::stick($urls);

制作完所有这些文件后,您可以通过以下 URL 访问您的微型框架:

http://localhost/glue

User Name: test

Password: test

我希望这能激励你,萨拉姆

参考:https ://github.com/jtopjian/gluephp

于 2015-11-10T18:43:16.287 回答