简体   繁体   中英

Laravel csrf token within PHP form

I created a little helper function for accepting friend requests. This function lies within a PHP file (obviously) and looks like this:

(Only the relevant part)

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

I know it's kind of messy. I'm fairly new to Laravel.

Anyway, there are two forms. One for accepting and one for denying the request. Now the thing I'm struggling with is the csrf token.

How do I implement this within the PHP helper file? I know how to use them in the blade templates, but I can't seem to make it work within the helper function.

Try to add _token hidden element to your code as below. You can also use csrf_token() helper function to add the form token inside forms.

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

You have added the fields, but you need to concatenate the csrf_token() value to your string. Right now, it will literaly print csrf_token as value.

Try this:

$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>';

Also, the csrf_field() function will echo an input field with the tokens value to the current request, csrf_token() will display only the token value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM