【问题标题】:Laravel csrf token within PHP formPHP表单中的Laravel csrf令牌
【发布时间】:2017-03-09 16:23:01
【问题描述】:

我创建了一个小助手函数来接受好友请求。该函数位于 PHP 文件中(显然),如下所示:

(仅相关部分)

foreach($friendrequests as $request){
    $username = DB::table('users')->where('id', $request->sender_id)->value('name');
    $notify .= '<li>';
    $notify .= '<strong><a href="/profile/'.$username.'">'.$username.'</a></strong><br>möchte dein Freund sein';
    $notify .= '<form action="/friend/request/accept/'.$request->sender_id.'" method="post"><input type="hidden" name="_token" value="csrf_field();"><button type="submit">Akzeptieren</button></form>';
    $notify .= '<form action="/friend/request/deny/'.$request->sender_id.'" method="post"><input type="hidden" name="_token" value="csrf_field();"><button type="submit">Ablehnen</button></form>';
    $notify .= '</li>';
}

我知道这有点乱。我对 Laravel 还很陌生。

无论如何,有两种形式。一种用于接受请求,一种用于拒绝请求。现在我正在努力解决的是 csrf 令牌。

如何在 PHP 帮助文件中实现这一点?我知道如何在刀片模板中使用它们,但我似乎无法使其在帮助函数中工作。

【问题讨论】:

    标签: php csrf laravel-5.4


    【解决方案1】:

    尝试将_token 隐藏元素添加到您的代码中,如下所示。您也可以使用csrf_token()helper function 在表单中添加表单令牌。

    foreach($friendrequests as $request){
            $username = DB::table('users')->where('id', $request->sender_id)->value('name');
            $notify .= '<li>';
            $notify .= '<strong><a href="/profile/'.$username.'">'.$username.'</a></strong><br>möchte dein Freund sein';
            $notify .= '<form action="/friend/request/accept/'.$request->sender_id.'" method="post"><input type="hidden" name="_token" value="'.Session::token().'"><button type="submit">Akzeptieren</button></form>';
            $notify .= '<form action="/friend/request/deny/'.$request->sender_id.'" method="post"><input type="hidden" name="_token" value="'.Session::token().'"><button type="submit">Ablehnen</button></form>';
            $notify .= '</li>';
        }
    

    【讨论】:

      【解决方案2】:

      您已添加字段,但您需要将 csrf_token() 值连接到您的字符串。现在,它将按字面意思打印csrf_token 作为值。

      试试这个:

      $notify .= '<form action="/friend/request/accept/'.$request->sender_id.'" method="post"><input type="hidden" name="_token" value="' . csrf_token() . '"><button type="submit">Akzeptieren</button></form>';
      

      另外,csrf_field() 函数会将带有令牌值的输入字段回显到当前请求,csrf_token() 将仅显示令牌值。

      【讨论】:

        猜你喜欢
        • 2014-05-17
        • 2020-03-22
        • 2011-09-25
        • 1970-01-01
        • 2017-04-13
        • 2017-12-12
        • 2017-10-18
        • 1970-01-01
        • 2016-12-08
        相关资源
        最近更新 更多