The PHP memory limit is the memory_limit configuration directive that sets the maximum amount of memory a single PHP script may allocate during one request or one command-line run. Among server resources on shared and dedicated servers, it acts as a per-process safety ceiling: when a script tries to exceed it, the engine aborts execution with the fatal error “Allowed memory size exhausted” instead of letting one runaway request consume the whole machine.
The directive does not reserve memory in advance. It is an upper bound on allocation, so a site with a 256 MB limit may use only 20 MB per request in normal operation. Understanding this distinction is essential for capacity planning, because the real memory footprint of a PHP application depends on how many worker processes run at once, not on the configured limit alone.
How the PHP memory limit is enforced
PHP enforces the limit inside its own Zend memory manager, which tracks every allocation made through the engine. Each time a script creates a variable, builds an array, loads a library or decodes a file, the manager adds the requested bytes to a running total and compares it with memory_limit. When the next allocation would cross the threshold, PHP raises an E_ERROR fatal error and terminates the script.
The counter is reset at the end of every request. With PHP-FPM or mod_php, a worker process serves many requests in sequence, but each request starts with a fresh budget. The value -1 disables the limit entirely, which is common for command-line tools such as Composer but dangerous for web requests.
Several details shape how the limit behaves in practice, and the following table summarizes them.
| Aspect | Behavior | Practical consequence |
|---|---|---|
| Scope | Per script execution | Ten parallel requests may each use the full limit |
| Accounting | Zend allocator only | Memory used by some C extensions may not be counted |
| Units | Bytes or K, M, G shorthand | A value of 256M equals 268,435,456 bytes |
| Value -1 | No limit | Acceptable for trusted CLI jobs, risky on the web |
| Error type | Fatal, not catchable | Shutdown functions still run, try/catch does not help |
Where memory_limit is configured
The directive can be set at several configuration layers, and the most specific layer usually wins. Knowing where a value comes from prevents the frequent situation in which an administrator raises the limit in one file while another file silently overrides it.
| Layer | Example syntax | Typical use |
|---|---|---|
| php.ini | memory_limit = 256M | Server-wide default for one PHP version |
| PHP-FPM pool | php_admin_value[memory_limit] = 512M | Per-site value that scripts cannot change |
| .user.ini | memory_limit = 384M | Per-directory override on shared hosting |
| .htaccess | php_value memory_limit 384M | Apache with mod_php only |
| Runtime | ini_set(‘memory_limit’, ‘512M’) | Raising the limit for one heavy task |
A php_admin_value setting in an FPM pool cannot be changed by ini_set(), which makes it the preferred tool for hosting providers that must keep tenants within agreed boundaries. Applications can confirm the effective value with ini_get('memory_limit') or by reading the output of phpinfo(), which shows both the local and master values.
PHP memory limit compared with related resource limits
The PHP memory limit is only one of several boundaries that can stop a request, and it is often confused with operating-system or container limits. The table below separates them by who enforces each limit and what happens when it is reached.
| Limit | Enforced by | Result when exceeded |
|---|---|---|
| memory_limit | PHP engine | Fatal error inside the script, worker survives |
| Container or cgroup limit | Linux kernel | OOM killer ends the process |
| CloudLinux LVE memory | Hosting kernel module | HTTP 503 or 508 errors for the account |
| Physical RAM and swap | Operating system | Heavy swapping, then OOM kills |
| Max execution time | PHP engine | Fatal error after a time budget, not a memory budget |
The decisive difference is graceful versus abrupt failure. A script that hits memory_limit produces a logged, readable error, while a process killed by the kernel often leaves only a brief log entry and a broken response. Setting the PHP limit below the container or account limit therefore keeps failures diagnosable.
Choosing a sensible memory_limit value
The right value is the peak memory of the heaviest legitimate request plus a safety margin, not the largest number the server can accept. Measuring with memory_get_peak_usage(true) in logs or using an application profiler reveals the real peaks, which are often far lower than administrators assume.
The limit also feeds directly into worker sizing. A rough upper bound for PHP-FPM is available RAM divided by the realistic per-worker footprint; using the limit itself in that formula gives a conservative worst case. If 4 GB is reserved for PHP and the limit is 256 MB, sixteen workers at full allocation would exhaust the budget.
| Workload | Common starting value | Reason |
|---|---|---|
| Simple website or API | 128M | Requests handle small data sets |
| CMS with plugins | 256M | Many libraries load on each request |
| E-commerce store | 256M to 512M | Catalog queries and checkout logic are heavier |
| Image processing | 512M or more | Decoded images need width × height × 4 bytes |
| CLI imports and builds | 1G or -1 | Long batch jobs process large files |
A practical rule is to raise the limit only for the code path that needs it. A nightly export can call ini_set() locally, while ordinary page views keep a modest server default that protects headroom for concurrent traffic.
Common mistakes and failure modes
Most problems with the PHP memory limit come from treating the symptom instead of the cause. A fatal memory error usually signals inefficient code, an unbounded query or a leak, and increasing the ceiling only postpones the next failure.
- Raising the limit blindly to 1G or -1 on web pools, which lets one bad request starve every other worker.
- Loading entire result sets into arrays instead of streaming rows with generators or cursors.
- Ignoring image dimensions: a 6000 × 4000 photo needs roughly 96 MB once decoded, regardless of its JPEG file size.
- Editing the wrong php.ini, because the CLI and FPM often read separate configuration files.
- Assuming the limit equals usage, which leads to overestimated hardware or underused servers.
A memory leak in a long-running process deserves special attention. Queue workers and daemons written in PHP accumulate allocations across jobs, so they should restart after a fixed number of tasks or when usage passes a threshold, rather than rely on an ever-higher limit.
In simple terms
Every time a PHP website builds a page, it borrows some of the server’s memory to do the work. The PHP memory limit is the maximum amount one page request may borrow. If a request asks for more, PHP stops it and reports an error.
Think of it like a spending limit on a company card. The limit does not mean each employee spends that much; it only stops one person from draining the whole account. A sensible limit protects everyone else on the server while still giving normal pages enough room to work.
A practical example
An online shop runs on a virtual server with 8 GB of RAM, PHP-FPM and a default limit of 128M. Each night an inventory import fails with “Allowed memory size exhausted”, and the developer is tempted to set the server-wide value to 1G.
Profiling shows that normal page views peak at about 45 MB, while the import loads a 300,000-row supplier file into one array. The administrator keeps the web pool at 256M, rewrites the import to stream rows in batches of 1,000, and runs it from the command line with its own 512M limit.
The outcome: the import finishes in a stable 180 MB, the web pool still supports about 24 workers within its RAM budget, and the nightly fatal errors disappear without exposing daytime traffic to runaway requests.