Php out of memory ошибка

Since my question is getting longer and longer, I decide to re-write the whole question to make it better and shorter.

I run my website on dedicated server with 8GB memory. I am fully aware that I need to raise the memory limit on php.ini setting. I have set it from 128M to 256M and to -1. Still the problem is persistence.

Fatal error: Out of memory (allocated 786432) (tried to allocate 24576
bytes) in D:wwwfootballviewsmain.php on line 81

The out of memory does not make sense because it said only 786432 bytes is allocated and it needed 24576 bytes more.

786432 bytes is only 768 kilobytes and is fairly small.

Hints

  • The error occurs on a very random line. It does not always error on line number 81.
  • At peak time, Apache only takes around 500mb of memory. I still have 6GB to spare.
  • There is no infinite loop.
  • The script takes 1,042,424 bytes. Getting this number from echo memory_get_peak_usage();
  • The resultset from MySQL is small (at most 12 of rows, purely text, no blob data)
  • (Important) If I restart Apache once every two days, the error is gone. It usually happens when Apache is running more than 2 days.
  • I have included the profiling the script and you can get it here.
  • This dedicated server is purely used to run only one website. This website is a high traffic website with average of 1,000 visitors every minute. At peak time, there will be 1,700 to 2,000 visitors accessing at the same time.

Server Spec

OS: Windows 2008 R2 64-Bit
CPU: Intel Core i5 — 4 cores
RAM: 8 GB
Apache 2.2
PHP 5.3.1
Storage: 2 x 1 TB hard drives
Bandwidth: 10 TB per month

Solution

I have finally tuned up and fixed the problem and I would like to share it here what I have done to improve:

  1. favicon.ico was missing which mess up with my route engine. Although my route engine is very small, but by including favicon.ico, it helps reduce memory usage by not running my route engine. Most of part of my website has it and I forgot to put it for this new section.
  2. Limit MaxRequestPerChild helps. In my other dedicated server, I have my MaxRequestPerChild limited. For this server, I set it to 0. I always thought that each script is isolated. Lets say if my script takes 800kb to run. Upon its completion, Apache or PHP should free 800kb memory. It seem like it doesn’t work this way. Limited MaxRequestPerChild does help to prevent memory leak by creating new process after limited MaxRequestPerChild and the old process is dying. This is my new setting.

    ThreadsPerChild      1500
    MaxRequestsPerChild  10000 
    
  3. ob_flush(); does reduce slightly more memory. It does not help much but every bit of optimization helps.

  4. I have used xdebug which I have never used before as suggested by people who attempt to answer this question. I have to say it is great tool and I have optimized a few stuffs to make it run slightly faster.
  5. I have disable a few unnecessary Apache module. I am trying to disable it one by one and leave it a few days test to ensure it works perfectly before I disable another one. I do have all unnecessary PHP extension disable now.
  6. Most of my script in this server used traditional way (no template, no database layer, pure PHP, HTML, and legacy mysql_* function). To be honest, it runs very fast and used extremely small memory. However, maintenance the script is not very easy as the website is getting longer. I have tried to convert some parts of the website into proper framework (my own tiny framework). The reason that I used my own framework because it is tiny (3kb for the whole framework and include only what I need).
  7. Switching to IIS7.5 solving this problem completely.

25

I ran accross the same kind of problem with the server dying when trying to use the swap. This is because mod_php does not free memory ever. So Apache processes keep growing either reaching apache or PHP’s memory limit or, if there’s no limit, crashing the server.

Restarting apache makes it to spawn new fresh slim processes but as they run PHP scripts over time, they grow until problems arise.

The solution is to make apache to kill processes after a certain number of queries served so it will create new ones ( There are some questions related to that) reducing the MaxRequestsPerChild configuration option to, let’s say 100 (Defaults to 1000).

Of course this may reduce server performances as it takes ressources to kill and spawn new processes but at least it keeps the site working. You might be tempted to raise the number of running processes to keep performances high, be sure PHP (or apache) memory limit x max number of processes do not get over your server’s physical ram.

Here’s my experience, hope it helps.

Community's user avatar

answered Aug 29, 2012 at 12:42

greg's user avatar

2

For starters, memory_get_peak_usage() will not be helpful here. It will only return the amount of memory which was allocated, and that is the same number which caused the error.

memory_get_usage will return the active amount of memory which is being allocated when it is called.

ini_set('memory_limit', '256M'); will set the maximum allowance of PHP’s footprint on your systems Memory. If you are getting OOM at 768K, upping it will not fix the problem.

There is no indication as to what version of PHP you are using, but I would suggest an upgrade immediately. There are several bugs where Zend’s Memory Manager fails to deallocate memory, which would lead you exactly to the same problem.

Are both your local server and your production server running the same version of OS, the same long bit and the same version of PHP? The answer will be no.

If it is unrelated to the windows malloc() issue, being it is a sub domain and probably within a VirtualHost, and allocating only 768k, it almost sounds like an OS issue.

Run tasklist from the command prompt when you access your script. Do you see an additional Apache thread, or Memory usage across the processes spike?

One last idea is, run flush() and/or ob_flush(); after each loop for the table row/column. This should clear your buffer and save you some memory in the event this is where the issue is occurring.

answered Aug 28, 2012 at 16:17

Mike Mackintosh's user avatar

Mike MackintoshMike Mackintosh

13.9k6 gold badges60 silver badges87 bronze badges

2

I would start by upgrading PHP to 5.4+ as it’s up to 50% faster for some applications.
They fixed a large number of memory leaks. Please see becnhamrks: http://news.php.net/php.internals/57760

answered Aug 27, 2012 at 8:55

maxwell2022's user avatar

maxwell2022maxwell2022

2,8185 gold badges41 silver badges60 bronze badges

1

Please note that the error is Out of memory and is not Allowed memory size [..] exhausted.

So the memory leak is elsewhere on the system. It’s possible that mysql server use a lot of system memory after this heavy query, leaving apache/php without it physical and swap.

This should explain the error always on the same line (and/or in the same script).

answered Aug 29, 2012 at 9:34

Luca Rainone's user avatar

Luca RainoneLuca Rainone

16k2 gold badges38 silver badges52 bronze badges

1

Install xdebug and enable profiler trigger.
Generate a profiler file, then post the cachegrind file if you still would not be able to tell the source of the problem.

EDIT: profiler file of the page where the memory leak happens of course!

answered Aug 27, 2012 at 9:10

Carmageddon's user avatar

CarmageddonCarmageddon

2,5554 gold badges34 silver badges56 bronze badges

2

Fatal error: Out of memory (allocated SOLVED
i had similar problem, for months no solution. finally i was checking in one of the apache folders i.e(apacheconfextra) i came across this file that controls the memory allocation of apache. the file name is httpd-mpm in that file you are to increase the MaxMemFree which is set 2048 to something higher, i took mine to 10000 for the first MaxMemFree (IfModule !mpm_netware_module) then made the second one MaxMemFree to 5000 IfModule mpm_netware_module.

These solved my problem. hope it helps

0

I would guess that you either haven’t edited the right php.ini or you haven’t restarted PHP and/or the webserver.

Create a phpinfo.php page in your docroot with the contents <?php phpinfo(); to make sure you are changing the correct php.ini. In addition to the location of the php.ini file the webserver is using, it will also state the maximum script memory allowed.

Next, I would add some stack traces to your page so you can see the chain of events that led to this. The following function will catch fatal errors and provide more information about what happened.

register_shutdown_function(function()
{
    if($error = error_get_last())
    {
        // Should actually log this instead of printing out...
        var_dump($error);
        var_dump(debug_backtrace());
    }
});

Personally, Nginx + PHP-FPM is what I have used for years since I left slow ol’ Apache.

3

Could be an issue with MySQL and the number of open connections, hence why it sorts itself out when you restart every few days. Are they auto closing on script shutdown?

answered Aug 29, 2012 at 14:07

Matt Humphrey's user avatar

Matt HumphreyMatt Humphrey

1,5541 gold badge12 silver badges30 bronze badges

1

Hey I also got the same problem on my server. I just changed the following things :

change php.ini to…

memory_limit = 128M

and add to httpd.conf

RLimitMEM 1073741824 2147483648

and restart apache & i removed the error :

Just to recap (I’m adding this answer quite a distance from the original question):

  • PHP is unable to allocate what appears to be a small amount of memory
  • the current memory usage at the time the error occrs + the requested amount is less than the memory limit currently in force
  • the system has 6Gb available for use by PHP when this occurs
  • since the problem is resolved by restarting apache — it’s apache which is preventing the memory from beig available to PHP

If these are all valid then the only possible explanation is that the 6Gb is very fragmented — which I think is a little unlikely. You didn’t say how PHP is invoked from Apache — mod_php? fpm? Fcgi?

I would start by examining each of the above predicates — particularly the free memory one. How do you know that there’s 6Gb free when the error occurs? A more likely cause is that there’s a memory leak occurring which you’re not spotting.

You’ve not provided any details of how apache is configured; I’d also have a look at reducing MaxRequestsPerChild and MaxMemFree. (I’m not very familiar with worker apache where this will apply per thread — really you need a limit per process). If you provided the core setting from the apache config then maybe we could make further suggestions.

Unless you are using Ajax extensively, make sure your keepalive time is 2 or less.

The following two facts definitely point to memory leaks:

  1. The error appears at different lines in your code,
  2. The error reports a relatively small memory allocation.

I would first single out PDO, disabling all the other extensions and let it run overnight using something like Siege / Apache Bench (ab). You could also try running it using the cli interface (just make sure you keep the same memory limits).

You could use the memory_get_peak_usage() function at the end of your script to see how much memory PHP thinks it has been using.

From your comment that’s 800 kB, which is okay; definitely not the gigantic amount of memory that would cause an out-of-memory ;-)

Lastly, though I wouldn’t recommend upgrading to 5.4 at this point, upgrading to the latest 5.3.x is probably worth it due to multiple vulnerabilities and leaks that have been addressed since 5.3.1

answered Aug 27, 2012 at 9:17

Ja͢ck's user avatar

Ja͢ckJa͢ck

170k38 gold badges263 silver badges309 bronze badges

2

this happened to me a few days ago. I did a fresh installation and it still happened. as far as everyone sees and based on your server specs. most likely it is an infinite loop. it could be not on the PHP code itself but on the requests made to Apache.

lets say when you access this url http://localhost/mysite/page_with_multiple_requests

Check your Apache’s access log if it receives multiple requests. trace that request and check out the code that might cause a ‘bottleneck’ to the system (mine’s exec() when using sendmail). The bottleneck im talking about doesn’t need to be an ‘infinite loop’. It could be a function that takes sometime to finish. or maybe some of php’s ‘program execution functions’

You might need to check ajax requests too (the ones that execute when the page loads). if that ajax request redirects to the same url

e.g. httpx://localhost/mysite/page_with_multiple_requests

it would ‘redo’ the requests all over again

it would help if you post the random lines or the code itself where the script ends maybe there is a ‘loop’ code somewhere there. imho php won’t just call random lines for nothing.

http://blog.piratelufi.com/2012/08/browser-sending-multiple-requests-at-once/

Most of the time you get such a error, problem is in code. I am not trying to say that you are writing code that is bad, I am trying to say that you need to carefully observe what’s there in that is using this much amount of memory.

Always remember «Garbage collection in PHP is pretty bad«, it’s not like Java, any other such language. there is a way to enforce garbage collection through gc_collect_cycle, but, in my personal opinion, that won’t solve your problem.
PHP free all memory used for executing a page, once request-response cycle is complete, so you may run into memory issues, if your script is long running, like a background script(Gearman etc), because, memory isn’t freed till script is running.

If above is not the case with your scr,pt, and as you said there is no code that requires such a huge amount of memory, then problem is most definitely in code it self, and upgrading to any version of PHP won’t solve the problem. I was facing with one of my Gearman scripts once, and there was a problem with one of my loop where I was appending one variable to one of my array, the variable itself was very heavy (approx 110KB of data). So I would suggest, do a careful inspection of your code.

Ravish

I had a similar problem with PHP:

1) Check your error logs. Eliminate EVERY error before continuing.
2) Consider modifying your apache configuration to eliminate unused modules — this will reduce the footprint needed by PHP — here’s a great link for this — it’s specific to WordPress but should still be very useful http://thethemefoundry.com/blog/optimize-apache-wordpress/

To give you an idea of the kind of bug I found, I had some code that was trying to post content to Facebook, Facebook then modified their API so this broke, I also used a ‘content expirator’ which basically meant that it kept retrying to post this content to Facebook and leaving loads of objects lying in memory.

1

From the profiler output file I’ve noticed a couple of things which I did not like/trust much and would look into these:

Apart from not knowing the meaning of the output numbers to detect an anomaly or how PHP scripts work…, Is this not a problem? Having an include to the same main.ph file, which looks like a recursive thing?

2121 fl=D:wwwfootballviewsmain.php
2122 fn=include::D:wwwfootballviewsmain.php

Noticed the file D:wwwfootballviewsmain.php is making use of some string functions several times, I guess it is calling these functions on the data returned by your query:

strlen
substr
strtotime

If, like in the C language, these functions require strings be null terminated or some other end of string terminator to avoid memory problems, I would look at the strings returned by your query.

Can you post the url of your website?

2

This is a known bug in PHP v 5.2 for Windows, it is present at least to version 5.2.3: https://bugs.php.net/bug.php?id=41615

None of the suggested fixes have helped for us, we’re going to have to update PHP.

Try to run php over fcgid, this may help:

These are the classic errors you will see when running PHP as an
Apache module. We struggled with these errors for months. Switching to
using PHP via mod_fcgid (as James recommends) will fix all of these
problems. Be sure you have the latest Visual C++ Redistributable
package installed:

http://support.microsoft.com/kb/2019667

Also, I recommend switching to the 64-bit version of MySQL. No real
reason to run the 32-bit version anymore.

Source: Apache 2.4.6.0 crash due to a problem in php5ts.dll 5.5.1.0

0

I would say the server is running out of physical/swap memory, so PHP can’t allocate enough memory.

Can you paste the output of free here?

answered Aug 27, 2012 at 21:54

Edson Medina's user avatar

Edson MedinaEdson Medina

9,7343 gold badges40 silver badges50 bronze badges

For my case, this error was triggered because of a huge select query (hundreds of thousands of returned results).

It arose immediately after adding millions of records in my Database to test the scalability of WordPress, so it was the only probable reason for me.

I know it’s an old thread, but here’s my experience getting it resolved.

My server is a hosted service running Apache.

My script crashed with out of memory at 6Mb, when my limit Was 256Mb — crazy, yeah?

It is being called synchronously via an http callback, from javascript running on my client, and crashed after around 550 calls.
After much time wasted with incompetent «Escalated Support» guys, my script now magically runs.

They said all they did was to reset php.ini, but I checked the differences:
enter image description here

No changes there that I can see that could have a bearing on an Out of Memory error.

I suspect a memory leak in the web server which my «Escalated Support» guy is hiding under the guise of resetting the php.ini. And, really, I’m not a conspiracy theorist.

Вылетает периодически ошибка:

Fatal error: Out of memory (allocated 3145728) (tried to allocate 2097152 bytes) in C:Program Filesxampphtdocssiteindex.php on line 92

при этом в нашем php.ini

memory_limit=1024M

Всё работает на xampp под Windows Server

при этом на серваке 32Гб ОЗУ.
А php загибается при попытке выделить 2 мегабайта (tried to allocate 2097152 bytes). Почему такое возможно?


  • Вопрос задан

    более трёх лет назад

  • 10573 просмотра

Выяснилось вот что:
Есть таблица. В таблице 70 000 записей. Общий объем таблицы = 7 Мб. Периодически происходит выборка всех этих записей, и запись их циклом через mysql_fetch_assoc() в массив. Out of memory происходит в основном во время работы этого цикла. Не справляется с записью такого объема данных в массив.

Переписали код. Ошибки перестали валиться.

Пригласить эксперта

Где-то циклическая зависимость скорее всего, вот и падает. Нужно смотреть что там в этом index.php

tried to allocate 2097152 bytes

Значит что память использовалась вся и на вот эти байты уже не хватило места, это не общий объем.
Включайте xdebug и отлаживайте, почти наверняка где-то бесконечный цикл.

У меня была такая проблема, при этом дебаг никак не помогал — память вылетала на абсолютно безобидных участках кода. Помогло обновление с PHP 5.3 до PHP 5.4.
П.С. Сайт был на вордпрессе.


  • Показать ещё
    Загружается…

09 июн. 2023, в 01:21

10000 руб./за проект

09 июн. 2023, в 01:06

50000 руб./за проект

09 июн. 2023, в 00:36

1000 руб./за проект

Минуточку внимания

fatal-error

Last night when I was moderating some comments on TechPP, I was shocked to see an error page instead of the admin panel dashboard. The error read something like this –

PHP Fatal error: Out of memory (allocated 49545216) (tried to allocate 77824 bytes) in /home/xxxxx/public_html/xyz/admin.php(1758) on line 40

The first thing I could think of was to restart the Apache httpd service. This immediately solved the issue. but I knew this is not a permanent fix for the issue. When I researched further, I got to know that the error comes when certain PHP scripts require more memory than PHP was allowed by default.

So the solution is to increase the memory allocated for PHP. How to do that? There are 4 possible ways –

1. Try looking for the php.ini file. You might find some redundant php.ini files, so make sure you have got the one which is actually being read by PHP. o be sure, create a new php file in your root folder, say “check.php” and have phpInfo(); within the php open and close tags. Execute this file to get the information on where the php.ini is residing. Normally it will be in /usr/local/lib/php.ini

Open the php.ini file in a text editor like TextPad (not in Notepad) and change the values for memory_limit. By default you should see memory_limit = 8M. Try changing it to 12M. If it doesn’t work, increase it to 16M or even 24M and so on.

2. In case you can’t find the php.ini file or do not have access to it, then open up the file which was throwing the error (admin.php in my case) and add a line below just after ini_set(’memory_limit’, ‘12M’);

3. You can even consider adding a line in .htaccess file which will resolve the issue.
php_value memory_limit 32M

4. Or else, Try adding this line to your wp-config.php file:
Increasing memory allocated to PHP
define('WP_MEMORY_LIMIT', '32M');

If none of the above things solve your issue, then talk to you host. If you have a host like Knownhost who is fast and knows what needs to be done, you do not have to worry much.

Note: I am now worrying on which PHP script required an increase in memory allocation. The analysis won’t be so easy though.

Image Courtesy: Clarkandransom

Was this article helpful?

YesNo

TechPP is supported by our audience. We may earn affiliate commissions from buying links on this site.

Did you ran into an error such as «LiteSpeed out of memory PHP» or «Fatal error: Out of memory», in this tutorial we will discuss how to fix this problem.

A strong, high-performance web server program that can manage a lot of traffic is called LiteSpeed Web Server. But if LiteSpeed PHP attempts to utilize too much RAM, it can get an out-of-memory problem. If the LiteSpeed out-of-memory PHP problem is something you are also experiencing, you are not alone. The identical problem has been reported by several users. The good news is that there are a few efficient fixes for this mistake.

What is LiteSpeed?

The top high-performance, high-scalability web server from LiteSpeed Technologies is called LiteSpeed Web Server. Without altering any other applications or operating system specifics, it may be used to replace an existing Apache server. The best part is that it may be fitted without causing any damage. As a result, LiteSpeed Web Server may easily take the place of a significant bottleneck in your current web hosting infrastructure.

LiteSpeed Web Server can assist you in overcoming the difficulties of implementing a successful web hosting infrastructure thanks to its extensive variety of capabilities and simple-to-use web management dashboard.

Advantages of LiteSpeed?

The performance of LiteSpeed Web Server is higher in terms of both speed and scalability. LiteSpeed serves PHP websites more quickly than Apache. Given that it quickly improves PHP’s performance and security, it makes an excellent hosting platform for websites powered by WordPress, Joomla, and Drupal.

Compatibility with Apache

The widely used Apache web server and its components, including mod rewrite, .htaccess, and mod security, are compatible with LiteSpeed Web Server. Even the Apache configuration files may be loaded by LiteSpeed Web Server, enabling it to function as an exact substitute for Apache.

Additionally, it works with popular hosting control panels including CyberPanel, cPanel, Plesk, and DirectAdmin.

Efficiency and Scalability

Through its distinctive event-driven design, LiteSpeed Online Server improves the speed & scalability of web hosting systems. It can handle thousands of clients concurrently while using the least amount of CPU and memory on the server. The LiteSpeed Web Server’s specially created and optimised code improves PHP speed and serves static webpages more quickly than Apache. It can manage unexpected traffic spikes and assist in managing against DDOS assaults without any DDOS mitigation hardware.

Security

The built-in anti-DDoS functionality of LitSpeed Web Server is interoperable with Apache’s mod security module. With the use of programmable features like per-IP connectivity and bandwidth throttling, attackers may be stopped before they can overwhelm your server by blocking IPs that make too many connections, requests, or bandwidth demands.

Cost Effective

It is simple to go from Apache to LiteSpeed, and it is also quite affordable in terms of support fees. When compared to any hardware modifications necessary to optimize an Apache server, the license expenses for LiteSpeed are extremely affordable. Additionally, by offering an efficient, secure, and dependable hosting infrastructure, LiteSpeed’s special capabilities aid in lowering support costs. In turn, this provides administrators and support staff peace of mind rather than having to cope with a server that is overcrowded.

What is PHP memory_limit?

PHP has a per-script memory limit that is enough for all web applications and is just like a regular memory limit. PHP scripts would currently generate errors stating that the memory limit had been exceeded if they attempted to use more than 32MB (which is default limit in CyberPanel).

To see the RAM limit, use the phpinfo() function, and then adjust your server settings in accordance with the result. The memory limit on the server can be set to -1, which means that no memory is assigned to any measurement (not recommended).

PHP scripts are quite short. Unless you have a unique application that requires more resources in one script than most applications will ever need in their whole, each script should only occupy a minimal amount of RAM.

Why Does Memory Have a Limit?

The number of concurrent processes that may run may be limited by increasing each process’s memory. The maximum number of page requests you may serve at once depends on PHP processes.

The memory limit serves to put a hard halt on PHP processes when they go out of hand before they crash your server or use all of your monthly resource allocations.

Genuine PHP programs tend to be somewhat compact. Unless you have a particular application that requires more resources in one script than the majority of programs will ever need in their whole, each script should only occupy a minimal amount of RAM. These plugins are undoubtedly available, but they are uncommon.

If you’re out of memory, there’s a good probability that one of your PHP programs is corrupt or malicious, which causes the memory limit error to appear.

However, perhaps you truly are utilising a huge plugin that requires additional RAM. Even if you are not installing a particularly resource-intensive programme, the error may still show because certain web servers have the PHP memory limit set to an extremely low value.

You’ll rapidly run into the memory exhausted problem in any case.

How To Fix «LiteSpeed out of memory PHP» or «Fatal error: Out of memory» Error?

This «LiteSpeed out of memory PHP» problem is extremely easy to fix using CyberPanel. Now to fix this problem, whether you are using LiteSpeed Enterprise or OpenLiteSpeed, you need to know your PHP version. So to find that out;

First of all, go to your CyberPanel Dashboard

LiteSpeed Out Of Memory PHP

Click on Website -> List websites from the left hand side menu. This will show the complete list of all the websites that you are using

Now scroll down to your site and against it’s name, you will see Manage. Click on that

Scroll down to vHost Conf. Click on it and scroll down to find out your PHP version.

Now that you know about your PHP version, it is time to fix the «LiteSpeed out of memory PHP» problem.

Fix «LiteSpeed out of memory PHP» problem on OpenLiteSpeed

Open your CyberPanel Dashboard

Click on PHP -> Edit PHP Configs from the left hand side menu

Select your PHP from the provided drop down menu

Increase your memory limit, also increase max_execution_time, upload_max_filesize, post_max_size and max_input_time. Now Click Save.

This will solve your problem. But if not, then you would need to increase your memory soft limit and memory hard limit. For that,

First of all, go to your CyberPanel Dashboard

Click on Website -> List websites from the left hand side menu. This will show the complete list of all the websites that you are using

Now scroll down to your site and against it’s name, you will see Manage. Click on that

Scroll down to vHost Conf. Click on it and scroll down to find memory soft limit and memory hard limit. Increase both as much required and click save.

Fix «Fatal error: Out of memory» problem on LiteSpeed Enterprise

Open your CyberPanel Dashboard

Click on PHP -> Edit PHP Configs from the left hand side menu

Select your PHP from the provided drop down menu

Increase your memory limit, also increase max_execution_time, upload_max_filesize, post_max_size and max_input_time. Now Click Save.

This will Solve your Problem. But if not, then you would need to increase your memory soft limit and memory hard limit using LiteSpeed Web Server

To learn about how you can web admin access to your LiteSpeed Web Server click here.

Open your Web Admin

Click on Configurations from the top bar and select Servers

Click on External App from the provided second top bar

Find your PHP version (you should know your PHP version for this as discussed above) and click Edit.

Scroll down to find the Memory Soft Limit and Memory Hard Limit. Change these values and save the changes

Click on Graceful restart from the top and restart your PHP. This will definitely resolve the «LiteSpeed out of memory PHP».

Conclusion

LiteSpeed Web Server is a powerful, high-performance web server application that can handle a lot of traffic. However, LiteSpeed may have an out-of-memory issue if it tries to use excessive amounts of RAM. You are not the only one who is encountering the LiteSpeed out-of-memory PHP issue. You may solve this problem with the aid of this article.

  • Главная

    Список форумов

    Модули и инструменты

  • Поиск

    • Текущее время: 09 июн 2023, 04:50
    • Часовой пояс: UTC+03:00

newd

Сообщения: 30
Зарегистрирован: 18 май 2012, 08:41

PHP Out of memory

Вчера столкнулся с проблемой при обработке больших файлов(200-300Мб)

Fatal error: Out of memory (allocated 157286400) (tried to allocate 345026221 bytes)

.
Думаю, да ладно — не беда. На ноуте 12 гигов память, выдам сколько надо.
Выставил мемори лимит в пхп.ини на 2 гига. Не помогло.
Выставил через ини_сет. Не помогло. Крутил вертел. Попробовал и 5.4 и 5.5 версии. В итоге так и не победил. Пришлось обрабатывать кусками по 50Мб.
На ноуте стоит Вин8.1.Оупен Сервер версии 5.1.1. Работа велась через консоль ConEmu.
Кто нибудь сталкивался с такими вылетами по причине нехватки памяти, когда памяти и выделено достаточно и физически достаточно?

Аватара пользователя

Максим

Сообщения: 6005
Зарегистрирован: 11 дек 2010, 20:29

Непрочитанное сообщение

Максим » 06 сен 2014, 14:09

newd, поменяйте параметр в шаблоне конфигурации, как и положено, и перезапустите сервер, после чего переоткройте консоль.

Аватара пользователя

Максим

Сообщения: 6005
Зарегистрирован: 11 дек 2010, 20:29

Непрочитанное сообщение

Максим » 06 ноя 2014, 21:37

CrazyPHP, в Windows 32-битный модуль PHP (который используется в Open Server) имеет максимальный лимит ~1.5 ГБ, а с учётом расширений PHP (intl, memcache,mongo, ioncube и т.д.) которые есть в Open Server и их настроек скрипту реально достаётся от 0.8 до 1.3 гигабайта максимум. Так что поставьте значение memory_limit = -1 это вообще отключит лимит. Если память нужна позарез, отключите все расширения PHP и расширения Zend (zend optimizer, ioncube, x-debug).

Если после выполнения этих настроек скрипту всё равно не получится занять более 1 гига памяти, то убедитесь что она у вас вообще есть, эта свободная память. Мало ли, может у вас в компьютере памяти всего 2 гига и открыто 100 вкладок в браузере.

Подождите ближайшего обновления Open Server, там будет 64-битный PHP не имеющий проблем с лимитами по памяти.

Аватара пользователя

Максим

Сообщения: 6005
Зарегистрирован: 11 дек 2010, 20:29

Непрочитанное сообщение

Максим » 19 ноя 2014, 04:27

Ошибочка вышла, до полутора гигов лимит, а не до двух. Выяснил только сейчас на тестах и потом уже полез в google. Поправил предыдущее сообщение.

P.S. В тестах интересное получил, особенно расширение php_intl «порадовало». Если в php.ini оставить только одну строку memory_limit = -1 то получится прочитать файл в строку размером 1.56 ГБ. Если же использовать тот php.ini что идёт изначально в комплекте с Open Server ничего не отключая, то у меня получилось читать файлы размером лишь чуть больше 800 мегабайт. Если отключить расширение php_intl то уже размером до 1.25 гига файлы спокойно прочитываются.

newd

Сообщения: 30
Зарегистрирован: 18 май 2012, 08:41

Непрочитанное сообщение

newd » 05 мар 2015, 21:00

Cервер с 64 битной версией php когда планируется?
Хочется без танцев с бубнами )

Аватара пользователя

Максим

Сообщения: 6005
Зарегистрирован: 11 дек 2010, 20:29

Непрочитанное сообщение

Максим » 06 мар 2015, 12:09

newd писал(а):Cервер с 64 битной версией php когда планируется?
Хочется без танцев с бубнами )

Должна была быть ещё на новый год. Но сначала я долго болел, потом началась запара по работе (и сейчас есть), поэтому к сожалению не могу найти времени сделать релиз. Думаю что в течении 2 недель будет, во всяком случае я постараюсь.

newd

Сообщения: 30
Зарегистрирован: 18 май 2012, 08:41

Непрочитанное сообщение

newd » 06 мар 2015, 19:44

Спасибо вам Максим! Что развиваете проект.
Я вчера прикрутил себе php5.5×64 + apache2.4×64 полет нормальный ))

AdeptO

Сообщения: 28
Зарегистрирован: 17 дек 2014, 22:57

Непрочитанное сообщение

AdeptO » 17 ноя 2015, 15:25

newd писал(а):PHP Out of memory

неподскажеш как? у меня щас такая проблема нифига непомагает

Понравилась статья? Поделить с друзьями:
  • Photoshop не открывает pdf ошибка диска
  • Photoshop exe ошибка приложения 0xc0000142
  • Photoshop exe ошибка приложения 0xc000007b
  • Photoshop cs6 ошибка при запуске приложения 0xc000007b
  • Photon launcher phasmophobia произошла одна или несколько ошибок