Php memory allocation for

How to Increase PHP Memory Limits

Why are PHP memory limits important to your website development journey? PHP is a famous backend technology that is used by many tech giants for supporting their applications. PHP gives many advanced features for making web pages dynamic and integrating some features you can not simply get using javascript, HTML, and CSS.

Whenever you set up a new PHP project, some memory is allocated automatically. This memory is mostly suitable for general applications. But there are some cases, for example when you are loading some heavy images when your website is using high graphics then you get some errors like —

“Fatal error: Allowed memory size of xxxxxx bytes exhausted” and

“filename.jpg exceeds the maximum upload size for this site.”

The best way to solve this error is to contact the hosting provider and increase the memory limit of the application. But there are ways to increase the memory limit of the whole website or a particular script without any expert help like using php.ini file, .htacess file, etc. In this blog, we will discuss the various strategies for increasing memory limit and the benefits of increasing the memory limit of your PHP application.

What is the PHP memory limit?

PHP memory limit is per script memory allotted to the PHP script. It is the same as the storage limit a particular task can occupy. This memory limit in PHP scripts is useful in some cases. For example, there can be cases when some poorly written code tries to eat up all the memory in the stack.

Most WordPress websites have a memory limit of 32M, but you may require more memory in many cases. For example, if you are doing heavy operations like recurring calls to the database and heavy image processing, you need to increase the memory limit of your script.

Strategies to Consider

In this part of the blog, we will share various ways to increase the memory limits of your PHP scripts/apps . While these are not the only ways to increase the memory limits of your PHP script, these are the ideal steps that most developers use for memory limit issues.

Also, changing the memory limit of an app can create problems sometimes, so you should always back up the data of your system.

Before trying to increase memory, you should always talk to the server providers of your website. They can help you increase the memory limit using their best practices.

Strategy 1: Edit the PHP.ini File

The php.ini file is executed every time a PHP application runs, and it’s used for controlling the various settings of PHP script like maximum upload size, memory limit, timeout limit, etc.

To increase the memory limit, you can change the following variables. But beware, these variables are case sensitive, and you need to restart the server after doing changes for them to be reflected.

memory_limit = 256M upload_max_filesize = 12M post_max_size = 13M file_uploads = On max_execution_time = 180

The max execution time refers to the timeout of the PHP script, and it means the maximum time for which the screen can be run.

Читайте также:  Java pack jars in jar

Strategy 2: Edit The HTAccess File

The .htacess file is a secret file hence its name starts with a dot. If you are using the shared hosting or, for some reason, you cannot access the php.ini file, you need to edit the .htacess file to increase the memory limit.

There are various use cases of this .htacess file. You need to add the following lines to this file to increase the memory limit.

php_value memory_limit 256M php_value upload_max_filesize 12M php_value post_max_size 13M

Strategy 3: Edit your wp-config.php File (If Working in WordPress)

Wp-config.php is one of the most critical files in WordPress sites. It is the configuration file of the WordPress sites.

For the memory limit, you can find a variable named WP_MEMORY_LIMIT in the config. Generally, the value of this is 32M. But you can increase the limit by altering this variable. For example, you can do something like this:

define('WP_MEMORY_LIMIT', '64M');

You can increase the memory to whatever limit you want and just save and close the config file to roll out the changes.

Strategy 4: Increase via CPanel

cPanel contains most of the information that is needed to run the website. If you cannot increase the memory limit using any one of the above methods, you need to increase it via the cPanel admin dashboard. So if you have access to cPanel, then to change the memory limit, follow the given steps:

  • Login to your cPanel admin dashboard. Then select the PHP version of your website.
  • Now go to options for this PHP version and find the memory limit column there.
  • There you can change easily change the memory limit of your PHP script, and your changes will be automatically saved.

Strategy 5: Increase via ini_set() Function

The ini_set() function is used to set the value of a particular attribute in the script’s context only. It is considered the safest of all the above ways because it only sets the value for the script particularly and restricts the poorly written scripts from consuming all the memory on the server.

To use this function to increase the memory limit, you can simply do.

ini_set('memory_limit', '512MB');

The above function will set the memory limit at 512 MB. Also, the ini_set() function is used only to set the value of a variable temporarily; once you close the script and restart it, it will take original values from the php.ini file.

Key Takeaways

There are many common errors like this memory limit one. In this blog, we have discussed the different strategies for increasing the memory limit in your script. The point to be noted here is that you should always raise the memory limit of your PHP script only as a last resort because this is a crucial task and can impact your site in many ways.

By the way, after making your website live to the actual customers, you must want to know what your users are doing on your website and the difficulties they are facing. It will help in increasing engagement and customer retention also. Scout APM is the best modern solution for the monitoring of your PHP application. It comes with support for many languages like PHP, Ruby, Python, etc. You will get 24×7 customer service, and pricing is very low compared to the market competitors.

Читайте также:  How to define variable in php

We also offer a 14-day free trial without any credit card. So if you want to scale your business to the next level, start your free trial now !

Источник

Memory management

The MySQL Native Driver manages memory different than the MySQL Client Library. The libraries differ in the way memory is allocated and released, how memory is allocated in chunks while reading results from MySQL, which debug and development options exist, and how results read from MySQL are linked to PHP user variables.

The following notes are intended as an introduction and summary to users interested at understanding the MySQL Native Driver at the C code level.

Memory management functions used

All memory allocation and deallocation is done using the PHP memory management functions. Therefore, the memory consumption of mysqlnd can be tracked using PHP API calls, such as memory_get_usage() . Because memory is allocated and released using the PHP memory management, the changes may not immediately become visible at the operating system level. The PHP memory management acts as a proxy which may delay releasing memory towards the system. Due to this, comparing the memory usage of the MySQL Native Driver and the MySQL Client Library is difficult. The MySQL Client Library is using the operating system memory management calls directly, hence the effects can be observed immediately at the operating system level.

Any memory limit enforced by PHP also affects the MySQL Native Driver. This may cause out of memory errors when fetching large result sets that exceed the size of the remaining memory made available by PHP. Because the MySQL Client Library is not using PHP memory management functions, it does not comply to any PHP memory limit set. If using the MySQL Client Library, depending on the deployment model, the memory footprint of the PHP process may grow beyond the PHP memory limit. But also PHP scripts may be able to process larger result sets as parts of the memory allocated to hold the result sets are beyond the control of the PHP engine.

PHP memory management functions are invoked by the MySQL Native Driver through a lightweight wrapper. Among others, the wrapper makes debugging easier.

The various MySQL Server and the various client APIs differentiate between buffered and unbuffered result sets. Unbuffered result sets are transferred row-by-row from MySQL to the client as the client iterates over the results. Buffered results are fetched in their entirety by the client library before passing them on to the client.

The MySQL Native Driver is using PHP Streams for the network communication with the MySQL Server. Results sent by MySQL are fetched from the PHP Streams network buffers into the result buffer of mysqlnd. The result buffer is made of zvals. In a second step the results are made available to the PHP script. This final transfer from the result buffer into PHP variables impacts the memory consumption and is mostly noticeable when using buffered result sets.

By default the MySQL Native Driver tries to avoid holding buffered results twice in memory. Results are kept only once in the internal result buffers and their zvals. When results are fetched into PHP variables by the PHP script, the variables will reference the internal result buffers. Database query results are not copied and kept in memory only once. Should the user modify the contents of a variable holding the database results a copy-on-write must be performed to avoid changing the referenced internal result buffer. The contents of the buffer must not be modified because the user may decide to read the result set a second time. The copy-on-write mechanism is implemented using an additional reference management list and the use of standard zval reference counters. Copy-on-write must also be done if the user reads a result set into PHP variables and frees a result set before the variables are unset.

Читайте также:  Example of HTML frame attribute with table

Generally speaking, this pattern works well for scripts that read a result set once and do not modify variables holding results. Its major drawback is the memory overhead caused by the additional reference management which comes primarily from the fact that user variables holding results cannot be entirely released until the mysqlnd reference management stops referencing them. The MySQL Native driver removes the reference to the user variables when the result set is freed or a copy-on-write is performed. An observer will see the total memory consumption grow until the result set is released. Use the statistics to check whether a script does release result sets explicitly or the driver does implicit releases and thus memory is used for a time longer than necessary. Statistics also help to see how many copy-on-write operations happened.

A PHP script reading many small rows of a buffered result set using a code snippet equal or equivalent to while ($row = $res->fetch_assoc()) < . >may optimize memory consumption by requesting copies instead of references. Albeit requesting copies means keeping results twice in memory, it allows PHP to free the copy contained in $row as the result set is being iterated and prior to releasing the result set itself. On a loaded server optimizing peak memory usage may help improving the overall system performance although for an individual script the copy approach may be slower due to additional allocations and memory copy operations.

There are multiple ways of tracking the memory usage of the MySQL Native Driver. If the goal is to get a quick high level overview or to verify the memory efficiency of PHP scripts, then check the statistics collected by the library. The statistics allow you, for example, to catch SQL statements which generate more results than are processed by a PHP script.

The debug trace log can be configured to record memory management calls. This helps to see when memory is allocated or free’d. However, the size of the requested memory chunks may not be listed.

Some, recent versions of the MySQL Native Driver feature the emulation of random out of memory situations. This feature is meant to be used by the C developers of the library or mysqlnd plugin authors only. Please, search the source code for corresponding PHP configuration settings and further details. The feature is considered private and may be modified at any time without prior notice.

User Contributed Notes

  • Mysqlnd
    • Introduction
    • Overview
    • Installation
    • Runtime Configuration
    • Incompatibilities
    • Persistent Connections
    • Statistics
    • Notes
    • Memory management
    • MySQL Native Driver Plugin API

    Источник

Оцените статью