Laravel - validate file size when PHP max upload size limit is exceeded
When your application relies on a shared hosting environment, you often hit hard ceilings imposed by the provider. In this specific scenario, the server's php.ini directive upload_max_filesize is locked at 5MB, and you lack the administrative privileges to raise it via ini_set(). While Laravel handles files under this limit gracefully, attempting to upload a larger file triggers an immediate Exception from the PHP runtime before your application's validation middleware ever gets a chance to inspect the payload. The error message is explicit: "The file exceeds your upload_max_filesize ini directive."
This behavior occurs because the PHP FPM engine rejects oversized files at the C-level, effectively short-circuiting the request lifecycle. Consequently, standard validation rules defined in Request::validate() or FormRequests cannot catch the file size if it breaches the server's hard limit. The exception is thrown during the parsing phase of the multipart form data, rendering the $request->file('image') property inaccessible for standard logic.
To solve this without modifying server configuration, you must shift your validation strategy from catching an exception to explicitly checking the request attributes before they trigger a fatal error, or by intercepting the response before it crashes.
Leveraging Request Attributes
Since the upload_max_filesize limit is enforced by PHP's HTTP handler, the file never technically enters the application's memory as a standard uploaded resource if it exceeds that threshold. However, Laravel provides access to the raw attributes of the incoming request through $request->attributes. Specifically, you can check the file attribute or inspect the _upload_max_filesize metadata if available in your specific server configuration.
More commonly, when this hard limit is hit, the exception class itself (Symfony\Component\HttpFoundation\File\Exception\FileException) contains the context of the failure. If you are using a custom controller or an API route, you can wrap your logic to catch the FileException and convert it into a user-friendly HTTP 413 Payload Too Large response.
use Illuminate\Http\Exceptions\HttpResponseException;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\Response;
public function upload(Request $request)
{
try {
// Attempt to access the file or validate standard rules
$validated = $request->validate([
'file' => 'required|file|max:5120', // Note: This check happens too late if PHP rejects it first
]);
// Logic to process the file
} catch (FileException $e) {
throw new HttpResponseException(
response()->json([
'message' => 'The uploaded file exceeds the server upload limit.',
'limit' => '5MB',
'status' => Response::HTTP_PAYMENT_REQUIRED // or 413 PAYLOAD_TOO_LARGE
], 413)
);
}
}
This approach acknowledges the hard constraint. You are essentially telling the user, "The server refuses this file regardless of what your code thinks." It prevents the ugly raw PHP error from bubbling up to the client.
Alternative: Client-Side Enforcement
If you have control over the frontend (JavaScript), the most robust solution is to enforce the limit there. By validating the file size in JavaScript before the form submission, you prevent the request from ever reaching the server if it is too large. This saves bandwidth and reduces unnecessary processing on the backend.
const maxSize = 5 * 1024 * 1024; // 5MB
if (file.size > maxSize) {
alert('File size exceeds the limit of 5MB.');
return;
}
This shifts the responsibility to the client, ensuring the server only receives compliant payloads. However, this is not foolproof; a malicious user could bypass the client-side check if they control the request stream directly (e.g., using curl), so server-side handling via exception catching remains necessary for API endpoints or untrusted sources.
Conclusion
When you cannot modify php.ini, treating the file size limit as an immutable constraint is the pragmatic engineering choice. You cannot "validate" a file that the PHP engine refuses to parse in the traditional sense. Instead, your code must be resilient enough to catch the resulting FileException and return a structured error message indicating the specific server limitation. This ensures a consistent API contract where the frontend handles size checks for convenience, and the backend handles the hard limits gracefully.
