Can you catch exceeded allocated memory error before it kills the script?

Posted by kristovaher on Stack Overflow See other posts from Stack Overflow or by kristovaher
Published on 2012-09-12T15:36:27Z Indexed on 2012/09/12 15:38 UTC
Read the original article Hit count: 237

The thing is that I want to catch memory problems before they happen. I have a system that gets rows from database and casts the returned associative array to a variable, but I never know what the size of the database result is is or how much memory it will take once the database request is made. This means that my software can fail simply because memory is exceeded.

But I want to avoid that somehow. One of the ways is to obviously make database requests that are smaller, but what if this is not possible or what if I do not know the size of data that is returned from database? Is it possible to 'catch' situations where memory use is exceeded in PHP? Something like this:

$requestOk=memory_test(function(){
    return doSomething();
});
if($requestOk){
    // Memory seems fine
    // $requestOk now has the value from memory_test() function
} else {
    // Function would have exceeded memory
}

I just find it problematic that my script can just die at any moment because of memory issues. From what I know, try-catch cannot be used here because it is a fatal error.

Any help would be appreciated!

© Stack Overflow or respective owner

Related posts about php

Related posts about memory