2017-03-09 178 views
0

我創建了一個小幫助函數來接受朋友請求。該功能位於一個PHP文件(顯然)內,看起來像這樣:PHP中的Laravel csrf令牌

(只有相關的部分)

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幫助程序文件中實現此操作?我知道如何在刀片模板中使用它們,但似乎無法在輔助函數中使用它們。

回答

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>'; 
    } 
1

您已添加字段,但需要將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()將只顯示令牌值。