0

PHP とGlue Frameworkで簡単なログイン システムを作成したいと考えています。私のコードは次のようなものです:

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問題は、これら 2 つの変数をどのようにキャッチpassして、それを PHP セッションに挿入できるかということです。

答えと説明をありがとう!

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.");
        }
    }
}

index.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

これがあなたにインスピレーションを与えることを願っています、SALAM

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

于 2015-11-10T18:43:16.287 に答える