How to get a warning about memory usage in PHP?

In PHP, when a script consumes more memory_limit, the script stops with an error. How to add a warning level: if my script consumes more than 90 MB, do I have a warning in the log file, but the script continues and still crashes if it consumes more than 128 MB?

I don't know anything about PHP extensions or PHP code, but while we are already building PHP on our own, we can even fix the code.

In Zend / zend_alloc.c, I see this

if (segment_size < true_size || heap->real_size + segment_size > heap->limit) {

It is really easy to add a line before this and compare the used memory with a different limit and issue a warning.

Can I do this in an extension or by fixing PHP code? Why does this not yet exist? It is a bad idea? Does it already exist somewhere?

Adding the same warning to MAX_EXECUTION_TIME seems more complicated as I still don't understand how the timer is handled.

+4
source share
2 answers

Here are some interesting questions / articles I found for you:

Basically, you can use PHP register_shutdown_functionto run the function when the script completes or stops. And the function error_get_last()returns information about the last error, which would be fatal:

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

I would not recommend that you simply edit the PHP C code. If you do not want to do this, this is PHP, then you really have to do the extension.

+1

php script, memory_get_usage(). , , script , , .

0

Source: https://habr.com/ru/post/1547609/


All Articles