Out of memory error reporting

When users upload very large photos and memory is tight, it seems like WordPress runs out of memory – fails to resize the uploaded photos and does not create the necessary metadata (_wp_attachment_metadata entry in wp_postmeta is not created).

The worst part is that the user is never notified. At most I get an “HTTP error” message.

Read More

Is is possible to somehow add an error message that will warn the user and remove the inconsistent file/database entries? How come this is not standard WP behavior?

Related posts

Leave a Reply

3 comments

  1. How do your users upload photos? You’re right about register_shutdown_function. It seems to work well in my code, though I only ever call my back-end via AJAX (I’ve also got file upload functionality), and so only need to account for this case. Here’s how I set it up in my plugin. Outside of the plugin class, somewhere at the bottom of the file, I have a function:

    function fatal_handler_ajax_wrapper() {
        $error = error_get_last();
        if( $error !== NULL) {
            $ret = array('status' => -1, 'msg' => 'Fatal error on server. Please contact server admin.');
            $errfile = "unknown file";
            $errstr  = "shutdown";
            $errno   = E_CORE_ERROR;
            $errline = 0;
    
            $ret['details'] = $error;
        }
        echo json_encode($ret);
    }
    

    In my plugin constructor I hook it up like this:

    function __construct() {
        register_shutdown_function( "fatal_handler_ajax_wrapper" );
        // ... whatever else you may need to do in your constructor
    }
    

    I’ve successfully tested it using this SO question‘s code (produces a nice fatal error). Put it somewhere inside your AJAX handler function in the back-end and watch the back-end return a nice JSON object to the front-end:

    $a = 'x';
    while (true) {
        $a = $a.$a;
    }
    

    Edit: just discovered from this SO question that register_shutdown_function will execute pretty much every time, even if there is no error. I’ve edited the code snippet to reflect this fact.

  2. I’m gonna add this as an answer, though it’s probably not the answer you want.

    The answer is “No, it is not possible”.

    Out of memory errors in PHP are fatal errors. There is no recovering from a fatality, and so no way to return a useful error message.

  3. @vancoders answer is right in general, but if you can impose restrictions on the size of the image then you can validate that the system will not fail, immediately after the image upload.

    The important thing here is not to check the file size itself but rather the dimension of the image, as the amount of memory required to prpcess it is bigger when the image in bigger.