Skip to main content

Safely catch a "Allowed memory size exhausted" error in PHP


I have a gateway script that returns JSON back to the client. In the script I use set_error_handler to catch errors and still have a formatted return.



It is subject to 'Allowed memory size exhausted' errors, but rather than increase the memory limit with something like ini_set('memory_limit', '19T') , I just want to return that the user should try something else because it used to much memory.



Are there any good ways to catch fatal errors?


Source: Tips4allCCNA FINAL EXAM

Comments

  1. As this answer suggests, you can use register_shutdown_function() to register a callback that'll check error_get_last().

    You'll still have to manage the output generated from the offending code, whether by the @ (shut up) operator, or ini_set('display_errors', false)



    ini_set('display_errors', false);

    error_reporting(-1);

    set_error_handler(function($code, $string, $file, $line){
    throw new ErrorException($string, null, $code, $file, $line);
    });

    register_shutdown_function(function(){
    $error = error_get_last();
    if(null !== $error)
    {
    echo 'Caught at shutdown';
    }
    });

    try
    {
    while(true)
    {
    $data .= str_repeat('#', PHP_INT_MAX);
    }
    }
    catch(\Exception $exception)
    {
    echo 'Caught in try/catch';
    }


    When run, this outputs Caught at shutdown. Unfortunately, the ErrorException exception object isn't thrown because the fatal error triggers script termination, subsequently caught only in the shutdown function.

    You can check the $error array in the shutdown function for details on the cause, and respond accordingly. One suggestion could be reissuing the request back against your web application (at a different address, or with different parameters of course) and return the captured response.

    I recommend keeping error_reporting() high (a value of -1) though, and using (as others have suggested) error handling for everything else with set_error_handler() and ErrorException.

    ReplyDelete
  2. you could get the size of the memory already consumed by the process by using this function memory_get_peak_usage documentations are at http://www.php.net/manual/en/function.memory-get-peak-usage.php I think it would be easier if you could add a condition to redirect or stop the process before the memory limit is almost reached by the process. :)

    ReplyDelete
  3. UPDATE

    This answer is insufficient for fatal errors -- the memory exhaustion problem in this case. The answer from @Bracketworks is a more correct way to do this sort of thing if you want to handle the error at the time it happens.

    I'm not deleting my answer here to hopefully help others avoid this mistake!



    I wasn't clear on whether or not you were already doing this, so here's how I would handle this problem:

    <?php

    // Create custom error handler that turns ALL php errors into Exceptions.
    // Then when an exception is caught you can decide how to handle it.
    function err_handler($severity, $message, $filepath, $line)
    {
    $msg = "$message in $filepath on line $line";
    throw new PhpErrException($msg);
    }

    // set your custom error handler
    set_error_handler('err_handler');

    // --- output json content type headers here ---

    try {

    // do stuff
    $json = '{ "errmsg": "", "value": "42" }';

    } catch (Exception) {
    if (strstr($e->getMessage(), 'Allowed memory size exhausted')) {
    $json = '{ "errmsg": "You are a MEMORY HOG!" }';
    } else {
    $json = '{ "errmsg": "Your request failed for an unkown reason" }';
    }
    }

    echo $json;

    ?>


    As for things like parse errors that you can't catch at runtime ... hopefully you've already eliminated those.

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.