check the array if it is empty or not that is received from the FORM that has CSRF generate token

csrf token laravel form
csrf token laravel ajax
csrf token mismatch
laravel refresh csrf token
laravel generate csrf token in controller
how csrf token works
disable csrf token laravel
csrf php

Since I am using csrf in the form, the array $data that is passed in request function is never empty. How to resolve this so that when i submit the form without any input fields filled, I get "data is empty"?

view.blade.php

<form action="{{url('/userdata')}}" method="POST">
    @csrf
    <div class="form-group">
        <label for="name">Name:</label>
        <input type="text" class="form-control" name="name">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
</form>

Controller.php

public function userdata(Request $request)
{
    $data=$request ->all();
    if(!empty($data)){
        echo "data is filled";
    }else{
        echo "data is empty";
    }
}

You can use required in the input fields if you don't want the form to submit empty.

<form action="{{url('/userdata')}}" method="POST">
    @csrf
    <div class="form-group">
        <label for="name">Name:</label>
        <input type="text" class="form-control" name="name" required>
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
</form>

Otherwise if name is your only field you can do this:

public function userdata(Request $request){
    $data = $request->except(["_token"]);
    if($data['name'] != ""){
      echo "data is filled";
    } else {
      echo "data is empty";
    }
}

Building PHP Applications with Symfony, CakePHP, and Zend Framework, To secure all forms that are generated with a controller, add this line at the top of it: public 'addresses'; var $components = array('Security'); function index($id = null) Unlike Symfony, CakePHP generates not one, but two CSRF tokens. /​csrf/cakephp/app/view/csrf/index.ctp The first one is placed after <form> start tag,​  The idea behind it is that when the server receives POST requests, the server checks for a CSRF token. If the POST request has a token that matches the active existing CSRF token created by the framework, the form is processed. If not, the form is not processed and an error is sent back to the client making the request.

You can use the get() method:

public function userdata(Request $request){
    $data = $request->get("_token");
    if(!empty($data)){
      echo "data is filled";
    } else {
      echo "data is empty";
    }
}

CSRF in Laravel: how VerifyCsrfToken works and how to prevent , From the early days of the internet there have been web attacks and the truth CSRF tokens are strings that are automatically generated and can be If not, the form is not processed and an error is sent back to the client making the request. When a request is received, the controller validates the request  CSRF (Cross-site request forgery) is type of attack, when attacker tries to send malicious requests from a website that user visits to another site where the victim is authenticated. Prevention from this attack is based on keeping security token during user’s session and providing it with every modify operation (PUT, POST, DELETE).

Sorry I misunderstood your question on my first answer. A value will always be submitted for input elements on the page, even if they're empty. The proper way to do this is to create a request validation.

Create something like this class, though much neater I'm sure ;)

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreUserdata extends FormRequest {
    public function authorize() {return true;}
    public function rules() {
        return ["name" => ["required", "max:64"]];
    }
}

And then edit the signature of your controller method so instead of expecting a Request it looks for your validation class (don't forget a use statement above):

public function userdata(StoreUserdata $request){
// ....
}

Now, your requests will fail if the name input is empty, or is too long. There are a lot of possible validation rules.

CSRF Protection - Laravel, Laravel automatically generates a CSRF "token" for each active user session a hidden CSRF token field in the form so that the CSRF protection middleware can will automatically verify that the token in the request input matches the token protection since Stripe will not know what CSRF token to send to your routes. // Check if a valid CSRF token was submitted with a form // // Generate a CSRF token for use when submitting a form however a cookie has not been set. Please

Class SecurityComponent, array. Controllers from which actions of the current controller are allowed to receive requests. Each form/page request will generate a new token that can only be submitted once array. Actions to exclude from CSRF and POST validation checks. has a CSRF token in the POST data and that the token is legit/not expired. In short, the following principles should be followed to defend against CSRF: Check if your framework has built-in CSRF protection and use it. If framework does not have built-in CSRF protection add CSRF tokens to all state changing requests (requests that cause actions on the site) and validate them on backend

How to validate CSRF token with session | Wiki, When you submit the form, Yii will compare two CSRF tokens from post and cookie. What Problem Will Happen ¶. 1.The user client DOES NOT  Defense Against CSRF, Step 1. The first line of defense that we can put in to defend against CSRF is to include a hidden token in any sensitive form submissions. This is commonly referred to as a CSRF Token. The only requirement for effective defense against CSRF is that it is unique per user.

Laravel: Up & Running: A Framework for Building Modern PHP Apps, if (auth()->check()) { // Do something } back() Generates a “redirect back” response, function () { if ($condition) { return back(); } }); collect($array) Takes an array and token value (csrf_token()) for adding CSRF verification to your form $var2, $state); // Why is this not working??? env($key, $default = null) Returns the  The main reason why CSRF protection is not included in other languages' session managers is technical limitation. Output buffering and buffered content rewriter is required for implementation. PHP has them both, but other languages do not. PHP is made for web and not utilizing ability would be a waste of features.

Comments
  • Thank you all for replying. I have found a solution for this using Validator. use Illuminate\Support\Facades\Validator; public function userdata(Request $request){ $data=$request->all(); $Validator=Validator::make($data,[ 'name' => 'required|max:255', 'mobile' => 'required|max:255', 'email' => 'required|max:255', ]); if ($Validator->fails()) { echo "data is empty"; }else{ echo "data is filled"; } }
  • You can't rely on client-side validation for security.
  • Thank you for the quick reply, but it still prints "data is filled". $data = $request->except(["_token"]); did not work
  • Is the form field disabled or otherwise removed from the HTML? If not, the form input will always be submitted even if it's empty.
  • No it is not disabled.
  • Ok then your request will always have a name element, even if it's just an empty string. Are you trying to validate the request to ensure it always contains a value? There are better ways to do that.
  • I am trying to insert the datas into database, if the form is not filled and submitted, it still enters with null values. So i was wondering if its because of the csrf the array is never empty