663

I have a bunch of client point of sale (POS) systems that periodically send new sales data to one centralized database, which stores the data into one big database for report generation.

The client POS is based on PHPPOS, and I have implemented a module that uses the standard XML-RPC library to send sales data to the service. The server system is built on CodeIgniter, and uses the XML-RPC and XML-RPCS libraries for the webservice component. Whenever I send a lot of sales data (as little as 50 rows from the sales table, and individual rows from sales_items pertaining to each item within the sale) I get the following error:

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 54 bytes)

128M is the default value in php.ini, but I assume that is a huge number to break. In fact, I have even tried setting this value to 1024M, and all it does is take a longer time to error out.

As for steps I've taken, I've tried disabling all processing on the server-side, and have rigged it to return a canned response regardless of the input. However, I believe the problem lies in the actual sending of the data. I've even tried disabling the maximum script execution time for PHP, and it still errors out.

Elrond_EGLDer
  • 47,430
  • 25
  • 189
  • 180
ArcticZero
  • 6,671
  • 3
  • 17
  • 8
  • 5
    I'm a bit confused... where does the error occur - in the client or server? And at which stage... client sending, server receiving, server processing, server sending, client receiving or client processing? – Greg Feb 18 '09 at 13:39
  • How/where are you setting the memory_limit to 1024M? – James Socol Feb 18 '09 at 14:20
  • 2
    The error seems to occur either during the client sending, or the server receiving. I've tried disabling all serverside processing, and rigging it to send a canned response regardless of the data sent. The error occurs if I send over a certain amount of data. I am changing the PHP.ini setting. – ArcticZero Feb 18 '09 at 16:04
  • Here is the code I am using... I have included the XML-RPC library used for the client as well: http://www.yousendit.com/download/U0d4SlIzcVg4aVBIRGc9PQ (Client) http://www.yousendit.com/download/U0d4SlIzcVhPSHhMWEE9PQ (Codeigniter Controller) Thanks for your time, in advance. :) – ArcticZero Feb 19 '09 at 04:54
  • 47
    memory limit is 128MB, souble it: `ini_set('memory_limit', '256M'); ` –  Aug 02 '13 at 10:49
  • 9
    Summary downvoted all the "just ignore the leak" answers, people who confused CodeIgniter with Drupal and people who just copy and pasted other peoples' answers to get points. The quality of answers in this one is abysmal. – Matti Virkkunen Dec 12 '13 at 09:38
  • 1
    Possible duplicate of [Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php](http://stackoverflow.com/questions/415801/allowed-memory-size-of-33554432-bytes-exhausted-tried-to-allocate-43148176-byte) – Damjan Pavlica Jul 06 '16 at 08:05

31 Answers31

750

Changing the memory_limit by ini_set('memory_limit', '-1'); is not a proper solution. Please don't do that.

Your PHP code may have a memory leak somewhere and you are telling the server to just use all the memory that it wants. You wouldn't have fixed the problem at all. If you monitor your server, you will see that it is now probably using up most of the RAM and even swapping to disk.

You should probably try to track down the offending code in your code and fix it.

Hassaan
  • 6,355
  • 5
  • 25
  • 44
Jeff
  • 8,125
  • 1
  • 16
  • 20
  • 180
    @Jeff you are probably right 95% of the time. However, there are times when you actually do need more memory. For example, let's say your app is loading a massive amount of data into memory for processing (say a Bill of Material with 15k components). It is not always the case that the code is buggy, sometimes you just need a little bit more memory (e.g. 256M instead of 128M). However I agree that setting it to -1 is horribly bad. But adjusting the memory limit for reasonable situations at run-time is perfectly acceptable imho. – Pyrite May 10 '14 at 18:52
  • 26
    @pyrite yes you are right that sometimes a process requires more memory but you should increase the memory limit to some logical amount like 256MB as you said or 512MB why not BUT not -1 ;) – Lukas Lukac Aug 18 '14 at 19:06
  • 9
    @jeff I fully agree, a value of `-1` could be useful **only** in dev environments to test purposes. – Esolitos Mar 03 '15 at 15:05
  • 4
    @Pyrite in the cases you named for the remaining 5% read the data in chunks and use a worker to process it instead of using more memory. This solution will scale as well while your suggestion won't work except your keep stuffing more and more memory into your server over the time if the data grows. – burzum Jul 12 '15 at 20:50
  • 4
    In most common way this trouble in ORM when you try to fetchAll data that much more php memory limit. For example when you try to generate monthly report. – Stepchik Jan 08 '17 at 16:21
  • There better solution not to store all data in memory and use database cursors and php yield, fetch data row by row and place it in your report. Here is small example with cursors and yield generators https://github.com/stepchik/stuff/tree/master/php_memory_problem – Stepchik Jan 08 '17 at 16:34
  • what to track on the fresh installation, error log just says that "Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 4096 bytes)" – Yogesh Trivedi Apr 10 '17 at 11:46
  • how to track it in localhost? – ehsan asarzadeh Oct 31 '20 at 10:50
  • Perfect answer . I like that. Cutting head is not a solution. it might be dangerous – Ariful Islam Apr 28 '21 at 06:08
212

ini_set('memory_limit', '-1'); overrides the default PHP memory limit.

hakre
  • 178,314
  • 47
  • 389
  • 754
Chris Lane
  • 3,297
  • 1
  • 11
  • 2
  • 1
    where should one change that?! I only find that line in php.ini – Alisso Mar 22 '13 at 08:28
  • 2
    In certain situations where you absolutely need something to complete and then change this back to a reasonable setting, this really helps. – DrCord Oct 04 '13 at 15:01
  • 16
    @williamcarswell; `-1` is a value PHP understands as *unlimited* in this context. – Alix Axel Nov 09 '13 at 12:27
  • 1
    combined with `max_execution_time = -1` this can consume all resources the server can spare. – baldrs Dec 23 '13 at 12:47
  • 7
    @ArseniuszŁozicki - it will also consume resources the server *can't* spare. – Ken Williams Feb 02 '14 at 03:48
  • 134
    Shame that this gets so many upvotes. Setting it to an accurate value, with either php.ini edits or ini_set, is a perfectly valid solution when people need more memory. Setting it to unlimited is a dangerous hack :( – Jeff Davis Mar 07 '14 at 15:38
  • 1
    @JeffDavis It's the best answer. I'm setting this a lot because I have PHP scripts I run on my desktop where I couldn't care less about the "dangerous" consequences. I just want to prevent the script from throwing that error, that's all. – user1767586 May 23 '14 at 20:57
  • 25
    @user1767586 then set it to a sane value. You could prevent the script from throwing the error by setting it to 1024M. If this answer said ini_set('memory_limit', '1024M'); You could copy-paste that and be ok. By setting it to -1 you are setting yourself up to have a script that consumes all memory. Especially if you do this routinely. Putting "dangerous" in quotes doesn't make it any less dangerous. You really could hose your host server. Maybe start destroying data. I don't know, maybe lose your job? Sounds pretty dangerous to me. :| – Jeff Davis May 26 '14 at 14:36
  • [`memory_get_usage(true)`](http://php.net/manual/en/function.memory-get-usage.php) may come handy if you are trying to figure out precisely **where** the memory outage is happening. This way you can try to improve your script performance without excessive memory consumption. – mathielo Nov 10 '14 at 18:46
  • 1
    this is not the correct way even this is much upvoted. this will lead to poor performance code. – albanx Apr 21 '15 at 12:14
  • 2
    With all due respect, this answer should be down-voted into oblivion. This solution "fixes" one problem, but introduces a host of other problems. It's like trading away the one devil you've got in return for dozens of more devils. As has already been suggested, (1) increase global PHP memory availability in ```memory_limit``` in ```php.ini``` and/or (2) diagnose the memory leak. – jfmercer May 06 '15 at 12:27
  • 4
    Sad to see that the answer for +161 votes and -3 votes is the same :( – akarthik10 Aug 21 '15 at 12:10
  • 2
    This is a very bad idea – user3806549 Dec 17 '15 at 15:38
  • Always think before you use this, if it is really neccessary. – kiltek Feb 15 '17 at 12:26
  • Works really well with high loaded production program, thanks infinitely ! – Mantisse Dec 14 '17 at 11:17
  • In case anyone with laravel project wonder where to put it! If the code is executing in web page call, then you need to put it in index.php in the very first line after – Ashiq Oct 15 '19 at 04:37
  • I was recieving this error locally within vscode, caused by my php extensions so it worked perfectly. – Lamellama May 11 '20 at 17:04
139

The correct way is to edit your php.ini file. Edit memory_limit to your desire value.

As from your question, 128M (which is the default limit) has been exceeded, so there is something seriously wrong with your code as it should not take that much.

If you know why it takes that much and you want to allow it set memory_limit = 512M or higher and you should be good.

Thusitha Sumanadasa
  • 1,521
  • 1
  • 20
  • 29
Basav
  • 2,575
  • 1
  • 17
  • 20
  • 7
    Honestly, if your caching some serious amounts of data, this is the correct answer. 128M is not enough for certain scripts. 512M or 1024M will often be enough, but you have to decide case by case. – Jeff Davis Mar 07 '14 at 15:36
  • 2
    Yeha, however try to avoid huge memory use, if the number of users are going to be more – Basav Jul 09 '14 at 10:23
  • 2
    memory_limit = -1 ; set in php.ini –  Aug 04 '14 at 18:24
  • 2
    @YumYumYum That removes the memory_limit, which you only want if you're monitoring memory usage some other way. The OS will kill the process if it's taking a huge amount of memory at some point any way. – Flimm Sep 10 '15 at 10:38
  • So if you are running a script that uses a lot of memory, but you only need to run it once, can you just increase the memory limit for the process at the time of execution, then lower your memory limit again after your one-time script runs? – chromechris Feb 16 '20 at 02:37
101

The memory allocation for PHP can be adjusted permanently, or temporarily.

Permanently

You can permanently change the PHP memory allocation two ways.

If you have access to your php.ini file, you can edit the value for memory_limit to your desire value.

If you do not have access to your php.ini file (and your webhost allows it), you can override the memory allocation through your .htaccess file. Add php_value memory_limit 128M (or whatever your desired allocation is).

Temporary

You can adjust the memory allocation on the fly from within a PHP file. You simply have the code ini_set('memory_limit', '128M'); (or whatever your desired allocation is). You can remove the memory limit (although machine or instance limits may still apply) by setting the value to "-1".

Luke Stevenson
  • 10,184
  • 2
  • 23
  • 41
Umair Idrees
  • 1,197
  • 1
  • 8
  • 5
  • 2
    Thank you I did not think to check if someone had set the value in .htaccess which was overriding php.ini and I couldnt figure out why +1 – HostMyBus Jun 16 '16 at 10:08
  • For anyone who needs set temporary with commands: `php -d memory_limit=256M your_php_file.php` or `php -d memory_limit=256M artisan ...` – The Anh Nguyen Dec 11 '20 at 06:12
64

It's very easy to get memory leaks in a PHP script - especially if you use abstraction, such as an ORM. Try using Xdebug to profile your script and find out where all that memory went.

troelskn
  • 107,146
  • 23
  • 127
  • 148
  • 1
    I'll go try Xdebug. I have never used it before, so I'll have to read up on it. Thank you for replying! Hope I find the answer to this soon... – ArcticZero Feb 18 '09 at 15:53
  • 35
    Remember that PHP uses reference counting for managing memory. So if you have circular references, or global variables, those objects won't get recycled. That's usually the root of memory leaks in PHP. – troelskn Feb 18 '09 at 16:08
  • Xdebug shows that CI's Xmlrpc.php library is responsible for my memory leak. By any chance, would there be any issues with CodeIgniter's XML-RPC libraries that I should know about? I have tried disabling all processing server-side, and it still runs out of memory if I feed it enough data. – ArcticZero Feb 18 '09 at 17:19
  • 1
    I don't know/use CI, so I don't know. But you should probably try to find an object that isn't freed up after use - most likely because of a cyclic reference. It's detective-work. – troelskn Feb 18 '09 at 21:58
  • I use ORM (doctrine) all the time and I haven't managed to have a single memory leak. – Alberto Gaona Jun 26 '14 at 03:44
  • 1
    This is the only answer here that advises actually addressing the problem. The other answers crank up memory to bandage over a *symptom* and ignore the *disease*. – Chris Baker Apr 25 '15 at 14:19
57

When adding 22.5 million records into an array with array_push I kept getting "memory exhausted" fatal errors at around 20M records using 4G as the memory limit in file php.ini. To fix this, I added the statement

$old = ini_set('memory_limit', '8192M');

at the top of the file. Now everything is working fine. I do not know if PHP has a memory leak. That is not my job, nor do I care. I just have to get my job done, and this worked.

The program is very simple:

$fh = fopen($myfile);
while (!feof($fh)) {
    array_push($file, stripslashes(fgets($fh)));
}
fclose($fh);

The fatal error points to line 3 until I boosted the memory limit, which eliminated the error.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
JamesAD-0
  • 679
  • 6
  • 6
  • 10
    you mean `ini_set('memory_limit', '8192M');` ? – Gogol Jan 06 '16 at 14:17
  • 3
    What a luxury it would be to have time to go and optimize a script for something like that. Or research and compare and learn ETL tools or some such. In the real world, we jack the memory allowance way up, do the thing, and move on. – Matthew Poer May 10 '18 at 02:58
48

I kept getting this error, even with memory_limit set in php.ini, and the value reading out correctly with phpinfo().

By changing it from this:

memory_limit=4G

To this:

memory_limit=4096M

This rectified the problem in PHP 7.

Danny Beckett
  • 18,294
  • 21
  • 100
  • 129
23

When you see the above error - especially if the (tried to allocate __ bytes) is a low value, that could be an indicator of an infinite loop, like a function that calls itself with no way out:

function exhaustYourBytes()
{
    return exhaustYourBytes();
}
Kristen Waite
  • 1,255
  • 1
  • 13
  • 26
21

Your site's root directory:

ini_set('memory_limit', '1024M');
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Gaurang P
  • 1,870
  • 1
  • 20
  • 20
21

You can properly fix this by changing memory_limit on fastcgi/fpm:

$vim /etc/php5/fpm/php.ini

Change memory, like from 128 to 512, see below

; Maximum amount of memory a script may consume (128 MB)
; http://php.net/memory-limit
memory_limit = 128M

to

; Maximum amount of memory a script may consume (128 MB)
; http://php.net/memory-limit
memory_limit = 512M
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Derick Fynn
  • 349
  • 2
  • 6
19

After enabling these two lines, it started working:

; Determines the size of the realpath cache to be used by PHP. This value should
; be increased on systems where PHP opens many files to reflect the quantity of
; the file operations performed.
; http://php.net/realpath-cache-size
realpath_cache_size = 16k

; Duration of time, in seconds for which to cache realpath information for a given
; file or directory. For systems with rarely changing files, consider increasing this
; value.
; http://php.net/realpath-cache-ttl
realpath_cache_ttl = 120

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
15

Change the memory limit in the php.ini file and restart Apache. After the restart, run the phpinfo(); function from any PHP file for a memory_limit change confirmation.

memory_limit = -1

Memory limit -1 means there is no memory limit set. It's now at the maximum.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Hasib Kamal
  • 1,971
  • 20
  • 26
14

In Drupal 7, you can modify the memory limit in the settings.php file located in your sites/default folder. Around line 260, you'll see this:

ini_set('memory_limit', '128M');

Even if your php.ini settings are high enough, you won't be able to consume more than 128 MB if this isn't set in your Drupal settings.php file.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
LK7889
  • 181
  • 1
  • 3
13

For Drupal users, this Chris Lane's answer of:

ini_set('memory_limit', '-1');

works but we need to put it just after the opening

<?php

tag in the index.php file in your site's root directory.

sigmapi13
  • 1,757
  • 2
  • 22
  • 25
13

Rather than changing the memory_limit value in your php.ini file, if there's a part of your code that could use a lot of memory, you could remove the memory_limit before that section runs, and then replace it after.

$limit = ini_get('memory_limit');
ini_set('memory_limit', -1);
// ... do heavy stuff
ini_set('memory_limit', $limit);
mykeels
  • 482
  • 5
  • 6
10

Just add a ini_set('memory_limit', '-1'); line at the top of your web page.

And you can set your memory as per your need in the place of -1, to 16M, etc..

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
  • 9
    This appears to say the same thing as many existing answers. It is best to only add an answer to a popular question only if the new material offers something novel. – halfer May 10 '19 at 11:20
7

PHP 5.3+ allows you to change the memory limit by placing a .user.ini file in the public_html folder. Simply create the above file and type the following line in it:

memory_limit = 64M

Some cPanel hosts only accept this method.

Farzad
  • 746
  • 2
  • 7
  • 26
Sabi
  • 79
  • 1
  • 1
7

Crash page?

Enter image description here

(It happens when MySQL has to query large rows. By default, memory_limit is set to small, which was safer for the hardware.)

You can check your system existing memory status, before increasing php.ini:

# free -m
             total       used       free     shared    buffers     cached
Mem:         64457      63791        666          0       1118      18273
-/+ buffers/cache:      44398      20058
Swap:         1021          0       1021

Here I have increased it as in the following and then do service httpd restart to fix the crash page issue.

# grep memory_limit /etc/php.ini
memory_limit = 512M
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
  • Which number (row and column?) one should look at after running the `free -m` command to decide on a new memory_limit? – kiradotee Jan 23 '20 at 17:48
6

For those who are scratching their heads to find out why on earth this little function should cause a memory leak, sometimes by a little mistake, a function starts recursively call itself for ever.

For example, a proxy class that has the same name for a function of the object that is going to proxy it.

class Proxy {

    private $actualObject;

    public function doSomething() {

        return $this->actualObjec->doSomething();
    }
}

Sometimes you may forget to bring that little actualObjec member and because the proxy actually has that doSomething method, PHP wouldn't give you any error and for a large class, it could be hidden from the eyes for a couple of minutes to find out why it is leaking the memory.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
madz
  • 1,543
  • 13
  • 36
  • And another tip: you can put `die('here')` in your code and move that statement around to see where the recursion starts. – toddmo May 06 '18 at 20:06
6

I had the error below while running on a dataset smaller than had worked previously.

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 4096 bytes) in C:\workspace\image_management.php on line 173

As the search for the fault brought me here, I thought I'd mention that it's not always the technical solutions in previous answers, but something more simple. In my case it was Firefox. Before I ran the program it was already using 1,157 MB.

It turns out that I'd been watching a 50 minute video a bit at a time over a period of days and that messed things up. It's the sort of fix that experts correct without even thinking about it, but for the likes of me it's worth bearing in mind.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
M61Vulcan
  • 169
  • 2
  • 5
  • I had a similar occurrence on Google Chrome today. I was extremely skeptical of this answer ...however, it did reveal that my byte exhaustion disappeared after I opened an incognito window and fired the same script again! The researching continues. – mickmackusa Apr 22 '20 at 23:52
3

Using yield might be a solution as well. See Generator syntax.

Instead of changing the PHP.ini file for a bigger memory storage, sometimes implementing a yield inside a loop might fix the issue. What yield does is instead of dumping all the data at once, it reads it one by one, saving a lot of memory usage.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
LukeDS
  • 141
  • 7
2

If you're running a WHM-powered VPS (virtual private server) you may find that you do not have permissions to edit PHP.INI directly; the system must do it. In the WHM host control panel, go to Service ConfigurationPHP Configuration Editor and modify memory_limit:

Updating memory_limit on WHM 11.48.4

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Fred Noriega
  • 329
  • 2
  • 7
2

I find it useful when including or requiring _dbconnection.php_ and _functions.php in files that are actually processed, rather than including in the header. Which is included in itself.

So if your header and footer is included, simply include all your functional files before the header is included.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Kerim
  • 1,007
  • 12
  • 11
2

Running the script like this (cron case for example): php5 /pathToScript/info.php produces the same error.

The correct way: php5 -cli /pathToScript/info.php

Jayme Brereton
  • 176
  • 2
  • 14
ratm
  • 825
  • 1
  • 10
  • 18
2

In my case on mac (Catalina - Xampp) there was no loaded file so I had to do this first.

sudo cp /etc/php.ini.default /etc/php.ini
sudo nano /etc/php.ini

Then change memory_limit = 512M

Then Restart Apache and check if file loaded

php -i | grep php.ini

Result was

Configuration File (php.ini) Path => /etc
Loaded Configuration File => /etc/php.ini

Finally Check

php -r "echo ini_get('memory_limit').PHP_EOL;"
DragonFire
  • 2,033
  • 1
  • 18
  • 33
1

The most common cause of this error message for me is omitting the "++" operator from a PHP "for" statement. This causes the loop to continue forever, no matter how much memory you allow to be used. It is a simple syntax error, yet is difficult for the compiler or runtime system to detect. It is easy for us to correct if we think to look for it!

But suppose you want a general procedure for stopping such a loop early and reporting the error? You can simply instrument each of your loops (or at least the innermost loops) as discussed below.

In some cases such as recursion inside exceptions, set_time_limit fails, and the browser keeps trying to load the PHP output, either with an infinite loop or with the fatal error message which is the topic of this question.

By reducing the allowed allocation size near the beginning of your code you might be able to prevent the fatal error, as discussed in the other answers.

Then you may be left with a program that terminates, but is still difficult to debug.

Whether or not your program terminates, instrument your code by inserting BreakLoop() calls inside your program to gain control and find out what loop or recursion in your program is causing the problem.

The definition of BreakLoop is as follows:

function BreakLoop($MaxRepetitions=500,$LoopSite="unspecified")
    {
    static $Sites=[];
    if (!@$Sites[$LoopSite] || !$MaxRepetitions)
        $Sites[$LoopSite]=['n'=>0, 'if'=>0];
    if (!$MaxRepetitions)
        return;
    if (++$Sites[$LoopSite]['n'] >= $MaxRepetitions)
        {
        $S=debug_backtrace(); // array_reverse
        $info=$S[0];
        $File=$info['file'];
        $Line=$info['line'];
        exit("*** Loop for site $LoopSite was interrupted after $MaxRepetitions repetitions. In file $File at line $Line.");
        }
    } // BreakLoop

The $LoopSite argument can be the name of a function in your code. It isn't really necessary, since the error message you will get will point you to the line containing the BreakLoop() call.

David Spector
  • 979
  • 7
  • 17
0

In my case it was a brief issue with the way a function was written. A memory leak can be caused by assigning a new value to a function's input variable, e.g.:

/**
* Memory leak function that illustrates unintentional bad code
* @param $variable - input function that will be assigned a new value
* @return null
**/
function doSomehting($variable){
    $variable = 'set value';
    // Or
    $variable .= 'set value';
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Dmitriy Kravchuk
  • 466
  • 4
  • 16
0

change ;memory_limit=512M to ;memory_limit=-1 in enter image description here

it's too dangerous for a server Your PHP code may have a memory leak somewhere and you are telling the server to just use all the memory that it wants. You wouldn't have fixed the problem at all. If you monitor your server, you will see that it is now probably using up most of the RAM and even swapping to disk.

Hossein Azad
  • 106
  • 8
0

I spent two dyas looking a solution for this and I figured out that this was cause in a call with PDO when I called

$stmt->bindParam(":PERIOD", $period); 

and the variables period was an

empty string ''

So this issue could have multiple root cause, my advice to you is that try a trial and error or a bisection method for a root cause finding, delete code and the try to search what is the line code that is failing

Update: I also faced this error with the method $pdo->query() I used $pdo->prepare() and worked well, so, while I had

$sql = "SELECT * FROM COURSE_DETAILS where ACTIVE = 1 AND COURSE_DETAILS_ID = $id";
$stmt = getConnection()->query($sql);
$courseDetails = $stmt->fetchAll(PDO::FETCH_ASSOC)

then i changed this to

$sql = "SELECT * FROM COURSE_DETAILS where ACTIVE = 1 AND COURSE_DETAILS_ID = ?";
$stmt = getConnection()->prepare($sql);
$stmt->execute(array($id)); 

and magically the memory error dissapeared!

Juan Pablo G
  • 581
  • 6
  • 7
0

This question was asked a few years ago, so although my facts are not the same, I also received this error recently when parsing a html table on server within loop. The reason for the error was because the html was parsed using double quotes that was concatenated to a variable $table, while simultaneously concatenating strings on multiline.

$table = "<table>\n";
    $table .= "<tbody>\n";
        foreach ($data as $item) {
            $table .= "<tr>\n";
                // this caused the Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted
                $table .= "<td>$item->description</td><td>$item->qty</td>" .  
                $table .= "<td>$item->price_incl</td><td>$item->price->vat</td>" .
                $table .= "<td>$item->price_excl</td><td>$item->available</td>" .
            $table .= "</tr>\n";
        }
    $table .= "</tbody>";
$table .= "</table>\n";

The above error was strange to me, but considering that I was already concatenating the string to the $table variable it now seems foolish that I had tried this. Solution was either to remove the variable concatenation on line 7 and 8 or to remove endline concatenation symbol from line 6, 7 and 8.

Hmerman6006
  • 606
  • 6
  • 17
-7

When I removed the following lines from my code, all worked OK!

set_include_path(get_include_path() . get_include_path() . '/phpseclib');
include_once('Net/SSH2.php');
include_once('Net/SFTP.php');

These lines were included in every file I was running. When running the files one by one, all worked OK, but when running all files together I got the memory leak issue. Somehow the "include_once" is not including things once, or I am doing something wrong...

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
  • 1
    `set_include_path(get_include_path() . get_include_path().'/phpseclib');` This will add the path '/phpseclib' once for each file that has the line... so it can add it many times! I'd suggest putting it in a settings file and `include_once` the settings file. – Farfromunique Jun 21 '17 at 18:05