发出 POST 请求时将 PHP 警告转换为 JSON

问题描述 投票:0回答:1

我有一个用于上传文件的服务器。它是一个使用 PHP 8.2 进行脚本编写的 Apache 服务器。我创建了一个表单,允许用户将图片和视频上传到服务器。现在,当我上传太大的文件时,我会返回一个通用 JSON 错误 400,简单地说“无法上传您的文件”。

上传失败时,Apache 会记录一个 PHP 错误,内容如下: PHP 警告:POST 内容长度 8978294 字节超出了第 0 行未知中 8388608 字节的限制。我希望能够捕获 PHP 在运行时生成的错误消息。

一旦捕获消息,我会添加一些条件以减少消息的特殊性,并可能将其更改为类似以下内容:文件太大,仅允许 XX 兆字节。然后我会将此消息一起返回给用户带有适当的状态代码。

现在,如果上传失败,PHP 警告错误将记录到 Apache,并且 PHP 脚本的其余部分将继续运行。通常,当您上传文件时,

$_FILES
常量将包含上传的数据,但是当上传太大时,
$_FILES
常量只是一个空数组。这意味着当我使用 try catch 块时,它永远不会抛出异常。

如何捕获此 PHP 错误,以便返回适当的 HTTP 状态代码和错误消息?

这是我处理 POST 请求的代码:

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'];

    $uploadPath = 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, $uploadPath . $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;
    }
}
php
1个回答
0
投票

警告在生产中不会可见,但您可以使用

set_error_handler
注册自定义错误处理程序并在那里返回 json 响应。

set_error_handler(function($errn, $errstr) {
  echo json_encode(['status'=>400,'message'=>errstr]);
  exit;
});
© www.soinside.com 2019 - 2024. All rights reserved.