I have a server that I am using to upload files. It is an Apache server that uses PHP 8.2 for scripting. I created a form that allows a user to upload pictures and videos to the server. Right now when I upload a file that is too large, I am returning a generic JSON error 400 that simply says “Failed to upload your file”.
When the upload fails a PHP error gets logged to Apache that says something like: PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0. I would like to be able to capture this error message generated by PHP during runtime.
Once I capture the message, I would add some conditionals to reduce the specificity of the message, and potentially change it to something like: File is too large, only XX megabytes allowed. Then I would return this message to the user along with an appropriate status code.
Right now if the upload fails, the PHP warning error gets logged to Apache and the rest of the PHP script continues to run. Normally when you upload files, the $_FILES
constant would contain the data for the upload, but when the upload is too large the $_FILES
constant is simply an empty array. This means that when I use a try catch block it never throws an exception.
How do I capture this PHP error so I can return an appropriate HTTP status code and error message?
Here is my code that handles the POST request:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
header('Content-Type: application/json');
$asset = $_FILES['file_data'];
//Stores the filename as it was on the client computer.
$assetName = $asset['name'];
//Stores the filetype e.g image/jpeg
$assetType = $asset['type'];
//Stores any error codes from the upload.
$assetError = $asset['error'];
//Stores the temp name as it is given by the host when uploaded.
$assetTemp = $asset['tmp_name'];
$assetPath = dirname(__DIR__, 1).'/uploads/';
$extensionsAllowed = ['png','jpg','jpeg','tiff','tif','webp','mp4','mp3','acc'];
$fileExtension = pathinfo($assetName, PATHINFO_EXTENSION);
if(array_search($fileExtension, $extensionsAllowed) !== false) {
echo json_encode(['status'=>415,'message'=>'Failed to upload your file']);
exit;
}
if(is_uploaded_file($assetTemp)) {
if(move_uploaded_file($assetTemp, $assetPath . $assetName)) {
echo json_encode(['status'=>200,'message'=>'Successfully uploaded '.$assetName);
exit;
}
else {
echo json_encode(['status'=>400,'message'=>'Failed to move your file']);
exit;
}
}
else {
echo json_encode(['status'=>400,'message'=>'Failed to upload your file']);
exit;
}
}