简体   繁体   English

处理得很好“POST内容 - 字节长度超过”警告限制

[英]Handle nicely “POST Content-Length of bytes exceeds the limit of” warning

Good day) I'm building a WordPress plugin LMS allowing user to attach their completed home assignments files via AJAX to their answers. 美好的一天)我正在构建一个WordPress插件LMS,允许用户通过AJAX将他们完成的家庭作业文件附加到他们的答案。 Everything works fine, except one scenario when user's file exceeds the maximum size allowed. 一切正常,但用户文件超过允许的最大大小的情况除外。 In this case my AJAX call returns HTML with following warning: 在这种情况下,我的AJAX调用返回HTML,并带有以下警告:

<b>Warning</b>:  POST Content-Length of XXXXX bytes exceeds the limit of XXXXX bytes in <b>Unknown</b> on line <b>0</b><br />

As this kind of warning generated on string 0 of my script, it will die and ignore any other instructions, leaving me this ugly string as a result of my call. 由于在我的脚本的字符串0上生成了这种警告,它会死掉并忽略任何其他指令,因为我的调用留下了这个丑陋的字符串。 You basically can live with it, as the final user will not see it (just the AJAX call will not have desired result), but still I want to know if there is a chance to jump it over and handle it nicely? 你基本上可以忍受它,因为最终用户不会看到它(只是AJAX调用没有期望的结果),但仍然想知道是否有机会跳过它并很好地处理它?

Ok, what kind of research I've already done: 好的,我已经做过什么样的研究:

  1. I found this tutorial by Andrew Curioso, and tried to make something like this from it: 我发现Andrew Curioso的这个教程,并尝试从中做出类似的东西:

     if (isset($_SERVER['CONTENT_LENGTH'])) { if ($_SERVER['CONTENT_LENGTH'] > (substr(ini_get('post_max_size'), -1) * 1024 * 1024)) { echo 'php errors is so much fun'; } } 

It doesn't give the desired effect, as my script still dies with only positive effect of echoing additional string from IF statement (besides, if you try to do something like wp_send_json(errorsArray), it will not be executed). 它没有产生预期的效果,因为我的脚本仍然只有从IF语句回显附加字符串的积极效果而死(此外,如果你尝试做类似wp_send_json(errorsArray)的事情,它将不会被执行)。

  1. Turning off displaying errors with display_errors, error_reporting. 使用display_errors,error_reporting关闭显示错误。 Well, it's not what I need here, as it still does not allow me to proceed with script and create custom error handler. 好吧,这不是我需要的,因为它仍然不允许我继续使用脚本并创建自定义错误处理程序。

  2. My WP_DEBUG is set to FALSE 我的WP_DEBUG设置为FALSE

What kind of advice I'm not looking for is manually editing max_upload_size, max_post_size etc. As manually editing server files is out of plugin philosophy. 我不想要的什么样的建议是手动编辑max_upload_size,max_post_size等。因为手动编辑服务器文件不符合插件的原则。 And anyway even if you set your max upload size to 10GB, once you will have final user trying to upload 11GB. 无论如何,即使您将最大上传大小设置为10GB,一旦最终用户尝试上传11GB。

SO, to summarize, as we all know, this mechanism is realized on thousands of sites and apps, and I want to know how to maximize my script quality, handling this issue without overkills and bad UX. 总而言之,众所周知,这种机制是在数千个网站和应用程序上实现的,我想知道如何最大限度地提高我的脚本质量,处理这个问题而不会出现过度杀伤和糟糕的用户体验。

Thank for sharing your thoughts :) 感谢分享您的想法:)

UPD1 Here is my AJAX call if it helps: UPD1如果有帮助,这是我的AJAX调用:

$('#post-assignment-answer').on('click', function (event) {
    event.preventDefault();

    tinymce.triggerSave();
    var answerContent = tinymce.get('assignment_user_input_textarea').getContent();

    var answerFile = $('#assignment-file-upload')[0].files[0];

    var formData = new FormData();

    formData.append('action', 'post_assignment_answer');
    formData.append('security', lucid_single_assignment_params.post_assignment_answer_nonce);
    formData.append('post_id', lucid_single_assignment_params.post_id);
    formData.append('answer_content', answerContent);
    formData.append('answer_file', answerFile);

    $.ajax({
        url: lucid_single_assignment_params.ajax_url,
        type: 'post',
        data: formData,
        contentType: false,
        processData: false,
        success: function (result) {
            console.log(result);
        }
    });
});

UPD2: Added AJAX handling php UPD2:添加了AJAX处理php

<?php

/**
 * Post Assignment Answer
 *
 * @version       1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
} // Exit if accessed directly

// Create AJAX call $result
$result = array(
    'fileTypeError' => false,
    'fileSizeError' => false,
    'uploadError' => false
);

// Retrieving current post ID
$post_id = $_POST['post_id'];

// Retrieving WYSIWYG content
$answer_content = '';

if (! (trim($_POST['answer_content']) == '') ) {

    $answer_content = wp_kses_post($_POST['answer_content']);

}

// Updating WYSIWYG meta field
update_post_meta($post_id, '_answer_content', $answer_content);

// Check if user intends to upload a file
if (!empty($_FILES['answer_file'])) {

    // Adding timestamp to file name
    $_FILES['answer_file']['name'] = round(microtime(true)) . '_' . $_FILES['answer_file']['name'];
    $answer_file = $_FILES['answer_file'];

    // Setting up uploaded file type validation
    $supported_types = array(
        'text/plain' // .txt
    );

    $arr_file_type = wp_check_filetype(basename($answer_file['name']));

    $uploaded_type = $arr_file_type['type'];

    // Setting up uploaded file size validation // TODO: This should be optimized
    $allowed_size = 8388608;
    $uploaded_size = $answer_file['size'];

    // Validating, and in a case of success completing upload
    if (!in_array($uploaded_type, $supported_types)) {

        $result['fileTypeError'] = __('The type of file you\'ve provided is not allowed', 'lucidlms');

    } elseif ($uploaded_size > $allowed_size) {

        $result['fileSizeError'] = __('The size of file you\'ve provided is exceeding the maximum upload size', 'lucidlms');

    } else {

        /**
         * Override the default upload path.
         *
         * @param   array   $dir
         * @return  array
         */
        function lucidlms_assignment_upload_dir( $dir ) {
            global $user_ID;

            return array(
                'path'   => $dir['basedir'] . '/lucidlms/assignment/user' . $user_ID,
                'url'    => $dir['baseurl'] . '/lucidlms/assignment/user' . $user_ID,
                'subdir' => ''
            ) + $dir;
        }

        // Register path override
        add_filter( 'upload_dir', 'lucidlms_assignment_upload_dir' );

        $upload = wp_handle_upload($answer_file, array( 'test_form' => false ));

        // Set everything back to normal
        remove_filter( 'upload_dir', 'lucidlms_user_upload_dir' );

        if (isset($upload['error']) && $upload['error'] != 0) {

            $result['uploadError'] = sprintf(__('There was an error uploading your file. The error is: %s', 'lucidlms'), $upload['error']);

        } else {

            // Check if there is an old version of file on the server and delete it
            $existing_answer_file = get_post_meta($post_id, '_answer_file', true);
            if (! empty($existing_answer_file)) {

                global $user_ID;
                $upload_dir = wp_upload_dir();
                $existing_answer_file_name = pathinfo($existing_answer_file['file'], PATHINFO_BASENAME);
                $unlink_path = $upload_dir['basedir'] . '/lucidlms/assignment/user' . $user_ID . '/' . $existing_answer_file_name;
                unlink($unlink_path);

            }

            // Updating post meta
            update_post_meta($post_id, '_answer_file', $upload);
        }
    }
}

wp_send_json($result);

Do read and understand what the error message is telling you: 请阅读并理解错误消息告诉您的内容:

exceeds the limit of XXXXX bytes in Unknown on line 0 超过第0行的Unknown中XXXXX字节的限制

The error is being reported at line 0 because it is being thrown before your PHP code gets to execute. 错误报告在第0行,因为它是 PHP代码执行之前抛出的。 So you can't change the behaviour in the receiving PHP script. 因此,您无法更改接收PHP脚本中的行为。

The right approach is to check the size of the data BEFORE you upload it (ie in Javascript). 正确的方法是在上传数据之前检查数据的大小(即在Javascript中)。 But beware: 但要注意:

  1. Javascript reports the size of individual files before they are encoded - Base64 encoding adds an overhead of around a third, plus space for other POST attribute values and names. Javascript 编码之前报告单个文件的大小--Base64编码增加了大约三分之一的开销,加上其他POST属性值和名称的空间。

  2. The values configured for post_max_size is the maximum that PHP accepts. 为post_max_size配置的值是PHP接受的最大值。 The maximum that the webserver (eg apache )will accept may be lower. Web服务器(例如apache )将接受的最大值可能更低。 For a plugin, perhaps the most appropriate solution would be to allow the administrator to configure the upper limit. 对于插件,最合适的解决方案可能是允许管理员配置上限。

  3. Someone trying to subvert your security can easily bypass any checks in Javascript 试图破坏您的安全性的人可以轻松绕过Javascript中的任何检查

Try this link : http://code.tutsplus.com/tutorials/uploading-files-with-ajax--net-21077 试试这个链接: http//code.tutsplus.com/tutorials/uploading-files-with-ajax--net-21077

In this at upload.php page (which is the main callback function of ajax which uploads the file) you will get the size of the image uploaded in $_FILES["images"]["size"] 在upload.php页面(这是上传文件的ajax的主要回调函数)中,您将获得上传到$_FILES["images"]["size"]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 文件上载警告发布内容的字节长度超出限制 - File Upload Warning post content-length of bytes exceeds the limit 警告:90612004 字节的 POST Content-Length 超出了第 0 行未知中 8388608 字节的限制 - Warning: POST Content-Length of 90612004 bytes exceeds the limit of 8388608 bytes in Unknown on line 0 如何避免:警告:POST内容长度47820076字节超过了第0行的Unknown中的8388608字节限制 - How to avoid: Warning: POST Content-Length of 47820076 bytes exceeds the limit of 8388608 bytes in Unknown on line 0 PHP 警告:8978294 字节的 POST 内容长度超出第 0 行未知中 8388608 字节的限制 - PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0 PHP警告:53160843字节的POST内容长度超过了行0上“未知”中的33554432字节的限制 - PHP Warning: POST Content-Length of 53160843 bytes exceeds the limit of 33554432 bytes in Unknown on line 0 PHP警告:POST内容 - n个字节的长度超过了第0行的Unknown中的3145728个字节的限制 - PHP Warning: POST Content-Length of n bytes exceeds the limit of 3145728 bytes in Unknown on line 0 无法解决:PHP警告:POST Content-Length的13110857字节超出了第0行上Unknown中的10485760字节的限制 - Cannot solve: PHP Warning: POST Content-Length of 13110857 bytes exceeds the limit of 10485760 bytes in Unknown on line 0 PHP 警告:113 字节的 POST 内容长度超出未知中 -1988100096 字节的限制 - PHP Warning: POST Content-Length of 113 bytes exceeds the limit of -1988100096 bytes in Unknown PHP 警告:8412174 字节的 POST Content-Length 超出了 Unknow 中 8388608 字节的限制 - PHP Warning: POST Content-Length of 8412174 bytes exceeds the limit of 8388608 bytes in Unknow 警告:11394639字节的POST内容长度超过了8388608字节的限制 - Warning: POST Content-Length of 11394639 bytes exceeds the limit of 8388608 bytes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM