Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate CSV file in Laravel [duplicate]

I am trying to upload a CSV file and I want to validate it before doing anything else. So I use the following code in my FormRequest:

public function rules()
{
    return [
        'csvFile' => 'required|file|mimes:csv'
    ];
}

The form i use for uploading the file is:

<form action="{{ route('uploadFile') }}" method="post" enctype="multipart/form-data">
    {{ csrf_field() }}
    <div class="form-group">
        <label for="fileToUpload">CSV File to upload</label>
        <input name="csvFile" type="file" class="form-control" id="fileToUpload" placeholder="Select file">
    </div>
    <button type="submit" class="btn btn-primary">Upload</button>
</form>

The problem is that it does not work. Trying to check the mime type of my test.csv file using getMimeType() I get:

"text/plain"

but if I use getClientMimeType() I get:

"text/csv"

From what I read is that:

The client mime type (getClientMimeType()) is extracted from the request from which the file was uploaded, so it should not be considered as a safe value.

For a trusted mime type, use getMimeType() instead (which guesses the mime type based on the file content).

Obviously, I should use getMimeType(), but it will not work (at least most of the times).

I tried to imitate this by doing:

end(explode('.', $file->getClientOriginalName()));

This will return 'csv' as a result, but it feels like a hack! Also, it can be fooled easily.

Is there a way to safely know if a file is of type .csv?

Thanks!

like image 824
christostsang Avatar asked Dec 20 '17 16:12

christostsang


2 Answers

you can use required|mimes:csv,txt for validation csv file.

like image 55
KaziBablu Avatar answered Sep 28 '22 03:09

KaziBablu


As CSV is basically a text-file, so its mime-type is checked against the file extension. Does your file have a .csv extension?

If you want to allow .txt extension as well, change your validation rule to this:

return [ 'csv_import' => 'required|mimes:csv,txt' ];
like image 33
Mizhar Raja Avatar answered Sep 28 '22 03:09

Mizhar Raja