ahangarha's avatar

Verify uploaded file/image

What is the best approach to verify if the uploaded file is a valid image file (either jpeg, webp, png) and not a malicious file with such extensions?

Using Laravel 8.

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

Validate the mimetype; Laravel delegates to Symfony's Mimetype guesser which reads the contents of the file rather than relying on the extension.

https://laravel.com/docs/8.x/validation#rule-mimetypes

$request->validate([
	// ...
	'image' => 'mimetypes:image/jpg,image/webp,image/png'
])l
1 like
ahangarha's avatar

And by this validation, I can be sure there is not malicious file uploaded to the server?

rovshena's avatar
use Illuminate\Http\Request;

public function upload(Request $request)
{
	//The file under validation must be an image (jpg, jpeg, png, bmp, gif, svg, or webp).
	$request->validate([
		'my_image' => 'image',
	]);

	if ($request->hasFile('my_image') && $request->file('my_image')->isValid()) {

		// upload

	}
}
1 like

Please or to participate in this conversation.