PHP Autoloading with Composer: PSR-4 Standard and Why It Matters for Code Organisation

11 min read 2,070 words
PHP Autoloading with Composer: PSR-4 Standard and Why It Matters for Code Organisation featured image

Understanding PHP Memory Limits and Execution Time Settings

PHP memory limit and execution time settings are server-level controls that prevent individual scripts from consuming excessive resources. These limits exist to protect server stability, but they can also block legitimate operations when a script needs to process more data than the defaults allow. Understanding how these settings work helps developers decide whether to adjust them, refactor the code, or investigate the underlying cause of the problem.

Most shared hosting environments set conservative defaults to ensure fair resource distribution between websites on the same server. VPS and dedicated server configurations typically give administrators more control over these values. Either way, hitting a memory or time limit usually signals that something in the script behaviour deserves attention.

What PHP Memory Limit Controls

The memory_limit directive sets the maximum amount of memory a PHP script can consume. When a script attempts to allocate more memory than this threshold, PHP stops execution and returns a fatal error like "Allowed memory size of X bytes exhausted".

The default value is often set to 128MB or 256MB on modern PHP versions. For basic websites running content management systems, this is usually sufficient. However, scripts that work with large datasets, image processing, XML parsing, or complex database queries can approach or exceed these limits during normal operation.

You can check your current memory limit by running a simple PHP script:

<?php
echo ini_get('memory_limit');
?>

Or by creating a file that outputs all relevant PHP configuration values:

<?php
phpinfo();
?>

What Execution Time Limits Control

The max_execution_time directive sets how many seconds a PHP script is allowed to run before the server terminates it. The default is typically 30 seconds. When this limit is reached, PHP returns a fatal error with the message "Maximum execution time of X seconds exceeded".

Scripts that take longer than expected often involve database queries that return large result sets, external API calls with slow responses, or loops that process data without proper output flushing. Long-running operations like importing bulk data, generating reports, or processing large files are common triggers.

Check your current execution time limit the same way:

<?php
echo ini_get('max_execution_time');
?>

Where These Settings Are Defined

PHP configuration values can be set in multiple locations, and they apply in a specific order of precedence:

  • php.ini: The main PHP configuration file. Changes here affect all websites on the server.
  • php-fpm.conf or www.conf: For servers running PHP-FPM, these files control pool-specific settings.
  • .htaccess: On Apache servers using mod_php, you can set values per directory.
  • wp-config.php or similar: Some applications allow configuration through their own files.
  • ini_set() in code: Scripts can change some values at runtime, though not all settings are overridable.

The method you use depends on your server access level and what you are trying to achieve. Shared hosting users typically rely on .htaccess or application-level configuration. VPS and dedicated server users can edit the main PHP configuration files directly.

How to Adjust These Settings Safely

Before increasing any limit, it is worth understanding why the script is hitting it in the first place. A script that needs 256MB of memory to load a page is not necessarily wrong, but it may be doing more work than necessary. Optimising the query, caching the result, or processing data in smaller chunks might resolve the issue without changing any settings.

Changing Settings in php.ini

If you have direct access to the server and need to apply a change globally, edit the php.ini file:

memory_limit = 256M
max_execution_time = 60

After saving the file, restart the PHP service for the changes to take effect. On Ubuntu servers running PHP-FPM, that typically means running:

sudo systemctl restart php-fpm

On Apache with mod_php, restart Apache instead:

sudo systemctl restart apache2

Changing Settings in .htaccess

For directory-level changes on Apache, add the directives to your .htaccess file:

php_value memory_limit 256M
php_value max_execution_time 60

This approach works on shared hosting where you do not have access to php.ini. Note that some hosting providers restrict which values can be changed via .htaccess for security reasons.

Changing Settings in Code

For runtime changes within a specific script, use ini_set() at the beginning of the file:

<?php
ini_set('memory_limit', '256M');
ini_set('max_execution_time', '60');

// Your script code here
?>

Keep in mind that ini_set() may be disabled on some hosting environments for security reasons. Also, certain system-level settings cannot be overridden at runtime even if the function is available.

Common Causes of Memory Limit Errors

Memory limit errors do not always mean the script is poorly written. Understanding the common causes helps determine the right fix.

  • Loading too much data at once: Fetching thousands of rows from a database without pagination or limits.
  • Large file operations: Reading or processing image files, PDFs, or exported data without streaming.
  • Recursive functions: Deep recursion on large datasets can consume memory quickly.
  • Unoptimised queries: Queries that load related data inefficiently or without proper indexes.
  • Memory leaks: Objects or data that persist in memory when they should be freed after use.

When debugging memory issues, PHP debugging tools like Xdebug with VS Code can help identify which functions are consuming the most memory during execution.

Common Causes of Execution Time Errors

Scripts that timeout before completing usually fall into a few predictable patterns.

  • Slow database queries: Queries without proper indexes, or queries that join many large tables.
  • External API calls: Waiting for responses from third-party services with slow response times.
  • Large data imports or exports: Processing thousands of records in a single request.
  • Missing pagination: Loading all results at once instead of processing them in batches.
  • Synchronous operations: Performing tasks sequentially that could run in parallel.

For performance-sensitive applications, load testing tools like k6 can help simulate realistic traffic and identify which operations are likely to timeout under load.

Refactoring Instead of Increasing Limits

Raising the memory limit or execution time is sometimes the right call. However, it is often a temporary fix that delays a deeper problem. When a script consistently needs more resources than the defaults allow, it usually benefits from refactoring.

Consider processing data in chunks rather than all at once. Use database pagination to limit result sets. Implement caching to avoid repeating expensive operations. Stream file uploads and downloads instead of loading them entirely into memory. These approaches reduce resource consumption and often improve overall application performance.

Settings That Cannot Be Changed at Runtime

Some PHP configuration values are classified as PHP_INI_SYSTEM, which means they can only be changed in php.ini or httpd.conf. The memory_limit directive is PHP_INI_ALL, so it can be changed anywhere. The max_execution_time directive is also PHP_INI_ALL in most PHP versions.

However, hosting providers sometimes restrict these changes at the application level. If ini_set() does not work on your environment, the setting may be locked at the server level.

What Happens When Both Limits Are Hit

A script can hit the memory limit before the execution time limit, or vice versa, depending on the operation. Memory errors typically occur during data processing, while timeout errors often occur during waiting, such as slow network calls or large database operations.

In some cases, a script may first exhaust memory and then fail to clean up properly before timing out, resulting in a confusing error message. Understanding which limit is the actual bottleneck requires testing and observation rather than assuming.

Logging and Monitoring for Recurring Issues

If the same script regularly hits these limits, it is worth adding logging to understand the pattern. Track which operations consume the most memory, how long specific functions take to execute, and whether the issue is getting worse over time as data grows.

For server-level monitoring, tools that track PHP-FPM process usage can help identify scripts that regularly approach or exceed configured limits. This data is useful for deciding whether to optimise the code, adjust server resources, or split long-running operations into background jobs.

Background Processing as an Alternative

For operations that genuinely require more time or memory than a web request should handle, moving the work to a background process is often a better approach than raising limits. Queue systems like RabbitMQ, Beanstalkd, or simple cron jobs can process heavy tasks outside the web request lifecycle.

This approach keeps web pages responsive, prevents timeout errors from affecting users, and allows the background worker to run with higher limits if needed. It is particularly useful for sending bulk emails, generating reports, importing data, and processing files.

Security Considerations When Adjusting Limits

Raising PHP limits too far can expose your server to abuse. An unlimited or very high memory limit means a compromised script or a malicious request could allocate all available memory and affect other sites or services on the same server. Similarly, a very long or unlimited execution time could allow a script to run indefinitely, tying up server resources.

Set limits conservatively and increase them only where there is a demonstrated need. Regularly review scripts that require higher limits to ensure they are working as intended and not consuming more resources than necessary.

When to Review Your PHP Configuration

PHP limit errors often surface during growth. A website that works fine with a hundred products may hit memory limits when it grows to ten thousand. Reviewing and adjusting configuration as part of regular maintenance helps prevent surprises during busy periods.

If your current setup regularly triggers these errors, a practical review of your PHP configuration and script behaviour can identify the root cause and determine whether adjustment, optimisation, or a different approach is most appropriate. Gather details about the specific error, the page or operation that triggers it, the size of your database, and how much traffic the site receives before reaching out for help.

Frequently Asked Questions

Can I set different memory limits for different websites on the same server?
Yes, if you use PHP-FPM. Each pool can have its own php_admin_value or php_value settings. This allows you to give specific sites more memory without affecting others on the server.
What is a safe maximum memory limit for WordPress or other content management systems?
Many content management systems recommend 256MB as a reasonable maximum. Some complex plugins or themes may need more, but anything above 512MB on a shared or mid-range VPS should prompt a review of what is consuming that memory.
Should I set max_execution_time to zero to prevent timeouts?
Setting max_execution_time = 0 removes the limit entirely. This is generally not recommended for web-facing scripts because a stuck or infinite loop will hang the request indefinitely. Use background processing for operations that genuinely need more time.
Why does ini_set not work for memory_limit on my hosting?
Some hosting providers disable ini_set() or restrict it for certain directives. In those cases, you need to ask your host to adjust the value, or use .htaccess if Apache mod_php is in use. On managed hosting, contact support to confirm what options are available.
Is it better to fix the code or raise the limits?
Fixing the code is usually preferable when the same operation consistently hits limits. Raising limits masks the symptom rather than addressing the cause. However, if the operation legitimately requires more resources and cannot be optimised further, a reasonable increase is appropriate.
How do I find out which script is causing the memory issue?
Use memory_get_peak_usage() in your PHP code to identify how much memory the script uses at its peak. Xdebug can generate memory profiles that show exactly which function calls consume the most memory. For quick checks, setting up Xdebug with VS Code provides an effective debugging environment.
Can raising memory limit improve website performance?
No, raising the memory limit does not improve performance. If anything, allocating more memory to inefficient scripts can mask problems that eventually get worse. Performance improvements come from optimisation, caching, and proper resource management.
Do PHP memory limits apply to CLI scripts?
Yes, memory limits apply to CLI scripts as well, though the default CLI php.ini often has different settings than the web php.ini. You can check the CLI-specific values with php -i | grep memory_limit or override them at runtime with the -d flag.