Reputation:
I have a simple infinite recursive code here:
<?php
function test() {
test();
}
test();
When I try to run the same, it eats up all the memory and eventually my laptop hangs. What I am looking for is a way to catch this and stop the machine from hanging. Is there any error handler in PHP for the same?
Things I have read and tried: setting max_execution_time to, let’s say, 5 seconds and catch the error line number. This didn’t work as proposed.
Is there another way to catch and stop this?
I am using Ubuntu 16.04.1 LTS (Xenial Xerus).
Upvotes: 1
Views: 3354
Reputation: 48745
Limit the shell subprocess memory usage:
Since you state you use Ubuntu, you can limit the memory for your processes:
$ ulimit -v 500000
$ php -r 'function test() { test(); } test();'
mmap() failed: [12] Cannot allocate memory
mmap() failed: [12] Cannot allocate memory
PHP Fatal error: Out of memory (allocated 304087040) (tried to allocate 262144 bytes) in Command line code on line 1
From PHP you can set the configuration option memory_limit:
$ php -r 'ini_set("memory_limit", "500MB"); function test() { test(); } test();'
PHP Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 262144 bytes) in Command line code on line 1
Now you can also edit the memory_limit in the default php.ini file or you can make a specific one for your script.
$ echo 'memory_limit = 500MB' > test.ini
$ php --php-ini test.ini -r 'function test() { test(); } test();'
Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 262144 bytes) in Command line code on line 1
You might want to copy the default one instead of having one just providing that one option.
Upvotes: 1
Reputation: 50200
If you need to limit the memory (rather than the CPU time) eaten up by your PHP process, see this question.
If you specifically want to limit the number of recursive call levels you allow... that's a different question, and I don't know of a way. But I'm surprised this would be a problem, because according to this question, PHP already has a 100-level recursion limit which should be enough to stop your script before it eats up significant memory.
Upvotes: 0
Reputation: 52
<?php
function test($tryCount=1){
$tryCount++;
//terminate recursive if more than 10 times loop
if($tryCount > 10){
return false;
}
test($tryCount);
}
test();
Upvotes: 0