4

In PHP, when the script consume more than memory_limit value, the script stop with an error. How can I add a warning level: if my script consumes more than 90Mb I have a warning in the log file, but the script go on, and still crashes if it consumes more than 128Mb?

I know nothing about PHP extensions or PHP C code, but as long as we already build PHP by ourself, we can even patch the code.

In Zend/zend_alloc.c I can see this

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

Really easy to add a line before this and compare used memory to another limit, and issue a warning.

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

Adding the same warning for MAX_EXECUTION_TIME seem more difficult, as I still don't understand the way the timer is handled.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Cédric Girard
  • 3,358
  • 7
  • 37
  • 52

2 Answers2

1

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

  1. This code shows a PHP way to catch a fatal error.
  2. Safely catch a 'Allowed memory size exhausted' error in PHP

Basically you can use the PHP register_shutdown_function to run a function when the script exits or stops. And the function error_get_last() returns information about the last error, which would of been the fatal one:

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 wouldn't recommend that you just edit the PHP C code. If you don't want to do this is PHP then you should really make an extension.

Community
  • 1
  • 1
beingalex
  • 2,416
  • 4
  • 32
  • 71
0

You could do it inside your php script using memory_get_usage(). It's not really at the system level and you'd have to call it several times while the script executes to catch the moment you use too much.

Community
  • 1
  • 1
cen
  • 2,873
  • 3
  • 31
  • 56
  • Well, I am a developper, but also a sysadmin, and it's not only "my" code, so I want to create a non fatal alert for the whole server. I am trying to patch PHP code, not very easy the first time. – Cédric Girard Jul 08 '14 at 15:27