Jump to content


This topic is now archived and is closed to further replies.


PHP CLI Freeing Memory

Recommended Posts

After much googling I'm stumped.

I have a PHP CLI application that runs as a constant background process on our server. As the process does its job it slowly builds up its memory usage. I've tried to combat this by using the unset() function on my objects that are no longer needed, but that doesn't help and I can't recover that memory. Has anyone else had this problem.

Here is a sample CLI script that shows the problem. I build up a good bit of memory while I'm processing and I'd like to free it when the job is done.

#!/usr/local/bin/php -c /usr/local/etc/php-cli.ini
class TestObj{
private $testArr;

public function __construct(){}
public function __destruct(){}

public function testme(){
$this->testArr = array();

for($i = 0; $i < 100000; $i++){
$something = "";

for($j = 0; $j < 10; $j++){
$something .= chr(rand(35,126) );
$this->testArr[$i] = $something;
$loop = true;

echo "Initial Memory Usage: " , memory_get_usage() , "\n\n";

echo "Creating New Object\n\n";
$test = new TestObj();
echo "Running Test Function\n\n";

echo "Ready to destroy object in...";
for($x=5 ; $x > 0; $x--){
echo $x, "...";


echo "\nSleepy Time\n";

// Sleep command so we can watch the memory


Share this post

Link to post
Share on other sites


Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.