Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running out of memory always on the same line

First of all, I am not looking for an answer saying "Check your PHP memory limit" or "You need to add more memory" or these kind of stuff ... I am on a dedicated machine, with 8GB of RAMS; 512MB of it is the memory limit. I always get an out of memory error on one single line :

To clarify: This part of the code belongs to Joomla! CMS.

function get($id, $group, $checkTime){
    $data = false;
    $path = $this->_getFilePath($id, $group);
    $this->_setExpire($id, $group);
    if (file_exists($path)) {
        $data = file_get_contents($path);
        if($data) {
            // Remove the initial die() statement
            $data   = preg_replace('/^.*\n/', '', $data); // Out of memory here
        }
    }
    return $data;
}

This is a part of Joomla's caching ... This function read the cache file and remove the first line which block direct access to the files and return the rest of the data.

As you can see the line uses a preg_replace to remove the first line in the cache file which is always :

<?php die("Access Denied"); ?>

My question is, it seems to me as a simple process (removing the first line from the file content) could it consume a lot of memory if the initial $data is huge? if so, what's the best way to work around that issue? I don't mind having the cache files without that die() line I can take of security and block direct access to the cache files.

Am I wrong?

UPDATE

As suggested by posts, regex seems to create more problems than solving them. I've tried:

echo memory_get_usage() . "\n";

after the regex then tried the same statement using substr(). The difference is very slight in memory usage. Almost nothing.

That's for your contributions, I am still trying to find out why this happen.

like image 363
Ahmad Alfy Avatar asked Dec 26 '22 05:12

Ahmad Alfy


1 Answers

Use substr to avoid the memory hungry preg_replace() , like this:

$data = substr($data, strpos($data, '?>') + 3);

As a general advice don't use regular expressions if you can do the same task by using other string/array functions, regular expression functions are slower and consume more memory than the core string/array functions.

This is explicitly warned in PHP docs too, see some examples:

http://www.php.net/manual/en/function.preg-match.php#refsect1-function.preg-match-notes http://www.php.net/manual/en/function.preg-split.php#refsect1-function.preg-split-notes

like image 105
Nelson Avatar answered Jan 06 '23 04:01

Nelson