使用Laravel 4实现"记住我"功能

Raf*_*del 1 php cookies remember-me laravel laravel-4

我是Laravel的新手,试着制作一个非常简单的登录表单.

此表单有一个"记住我"复选框.我尝试使用Cookie::make()它来实现它的功能但事实证明我需要返回一个Response以便保存它.

当我检查存储localhost在浏览器中的cookie时,我找不到名为的cookie username.我做了一些研究,结果发现我必须将cookie附加到a Response然后返回它.

问题是,我不想退货Response!!

我还没有达到Auth我的学习过程中还级.所以不使用这个类的解决方案会更合适.

这是我的代码:

public function processForm(){
    $data = Input::all();
    if($data['username'] == "rafael" & $data['password'] == "123456"){
        if(Input::has('rememberme')){
            $cookie = Cookie::make('username', $data['username'], 20);
        }
        Session::put('username', $data['username']);
        return Redirect::to('result');
    } else {
        $message_arr = array('message' => 'Invalid username or password!');
        return View::make('signup', $message_arr);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的signup.blade.php:

@extends('layout')

@section('content')
    @if(isset($message))
        <p>Invalid username or password.</p>
    @endif
    <form action="{{ URL::current() }}" method="post">
        <input type="text" name="username"/>
        <br>
        <input type="text" name="password"/>
        <br>
        <input type="checkbox" name="rememberme" value="true"/>
        <input type="submit" name="submit" value="Submit" />
    </form>
@stop
Run Code Online (Sandbox Code Playgroud)

routes.php :

Route::get('signup', 'ActionController@showForm');

Route::post('signup', 'ActionController@processForm');

Route::get('result', 'ActionController@showResult');
Run Code Online (Sandbox Code Playgroud)

ehp*_*ehp 5

您应该查看Laravel 4关于用户身份验证的文档,可以在以下位置找到:

http://laravel.com/docs/security#authenticating-users

基本上,您可以通过将$ data传递给Auth :: attempt()来验证用户身份.将true作为第二个参数传递给Auth :: attempt()以记住用户以便将来登录:

$data = Input::all();

if (Auth::attempt($data, ($data['rememberme'] == 'on') ? true : false)
    return Redirect::to('result');
else
{
    $message_arr = array('message' => 'Invalid username or password!');
    return View::make('signup', $message_arr);
}
Run Code Online (Sandbox Code Playgroud)

您应该使用Laravel的方法进行身份验证,因为它会处理密码提醒等.