Laravel: Rate-Limit API Routes with Throttle
Protect your Laravel API from abuse with the built-in throttle middleware — limit requests per minute per user or IP.
Validate file uploads in PHP by checking the real file type, size and extension — not just what the browser claims.
29 lines · Updated Nov 26, 2026
<?php
// Laravel: in a Form Request or controller
$request->validate([
'photo' => [
'required',
'file',
'image', // checks the real MIME type
'mimes:jpg,jpeg,png,webp',
'max:2048', // 2 MB
'dimensions:min_width=200,min_height=200',
],
]);
// Plain PHP: check the real type with finfo
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($_FILES['photo']['tmp_name']);
$allowed = ['image/jpeg', 'image/png', 'image/webp'];
if (! in_array($mime, $allowed, true)) {
die('Only JPG, PNG and WebP images are allowed.');
}
if ($_FILES['photo']['size'] > 2 * 1024 * 1024) {
die('File is larger than 2 MB.');
}
$path = 'uploads/' . bin2hex(random_bytes(8)) . '.jpg';
move_uploaded_file($_FILES['photo']['tmp_name'], $path);
File uploads are one of the most dangerous features on any website. If an attacker can upload a .php file disguised as an image and then open it in the browser, they can take over your server. This snippet validates uploads properly in PHP: it checks for upload errors, limits the size, detects the real file type from its contents, and stores the file under a safe, random name.
finfo instead of trusting the file extension or the browser-provided type, which attackers can fake.move_uploaded_file().php.ini (upload_max_filesize, post_max_size) and your web server.../.post_max_size, so $_FILES is empty.Laravel? Use validation rules like file|mimes:jpg,png,pdf|max:2048 and store with $request->file('x')->store(), which generates a random name.
Related: OWASP Top 10 explained · Bulk image resizer
In Laravel, use the validation rules in a Form Request. In plain PHP, use the finfo block before move_uploaded_file. Always store uploads outside the public folder or under a random name.
Share this snippet
Protect your Laravel API from abuse with the built-in throttle middleware — limit requests per minute per user or IP.
Generate a sitemap.xml from your database in Laravel — always up to date, no file to maintain by hand.
Send WhatsApp messages from Laravel through a provider API — order updates, OTPs and alerts in a few lines.