I knew this question may sound duplicate but am just in a mess.
Iam new to Laravel. coming from php background. I am using the code below to validate image in laravel 5.7.8. it does validation by checking the file extension name, size etc. Now I want to check the mimetype as a way securing the file upload hence the code
$rules= [
'file' => 'mimes:jpeg,bmp,png,gif'
];
$x = $request->all();
$validator=Validator::make($x, $rules);
if ($validator->passes()){
Session::flash('message','File Uploads successful.');
}else{
Session::flash('message','Invalid File type .');
}
My problem is that its not returning error message eg Invalid File type when an invalid file is uploaded.
Below is how I added it to my main controller. All other checking are okay. I just want the code to print Invalid File type whenever a file that is not image is being uploaded
<?php
namespace App\Http\Controllers;
use Session;
use Validator;
use Illuminate\Http\Request;
class PictureController extends Controller{
public function picture(){
return view('picture');
}
public function uploadFile(Request $request){
if ($request->input('submit') != null ){
$file = $request->file('file');
// File Details
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$tempPath = $file->getRealPath();
$fileSize = $file->getSize();
$mimeType = $file->getMimeType();
//dd($mimeType = $file->getMimeType());
// Valid File Extensions
$valid_extension = array("jpg","jpeg","png");
//validate files uploads mimetype
$rules= [
'file' => 'mimes:jpeg,bmp,png,gif'
];
$x = $request->all();
$validator=Validator::make($x, $rules);
// 2MB in Bytes
$maxFileSize = 2097152;
// Check file extension
if(in_array(strtolower($extension),$valid_extension)){
// validate mimetype
if ($validator->passes()){
// Check file size
if($fileSize <= $maxFileSize){
// File upload location
$location = 'images';
// Upload file
$file->move($location,$filename);
Session::flash('message','Upload Successful.');
}else{
Session::flash('message','File too large. File must be less than 2MB.');
}
//validator starts
}else{
Session::flash('message','Invalid File type');
}
//validator ends
}else{
Session::flash('message','Invalid File Extension1.');
}
}
// Redirect to index
return redirect()->action('PictureController@picture');
}
}