0
0
PhpHow-ToBeginner · 3 min read

How to Increase Memory Limit in PHP: Simple Steps

To increase the memory limit in PHP, you can change the memory_limit setting in the php.ini file or use ini_set('memory_limit', '256M') in your script. Alternatively, you can set it in an .htaccess file with php_value memory_limit 256M if your server allows it.
📐

Syntax

The memory limit in PHP can be set using the memory_limit directive. You can set it in three main ways:

  • php.ini file: memory_limit = 256M sets the limit to 256 megabytes.
  • ini_set() function: ini_set('memory_limit', '256M'); sets it during script execution.
  • .htaccess file: php_value memory_limit 256M sets it for Apache servers.
ini
memory_limit = 256M

// or in PHP script
ini_set('memory_limit', '256M');

# or in .htaccess
php_value memory_limit 256M
💻

Example

This example shows how to increase the memory limit to 256MB inside a PHP script and then display the current memory limit.

php
<?php
ini_set('memory_limit', '256M');
echo 'Current memory limit: ' . ini_get('memory_limit');
?>
Output
Current memory limit: 256M
⚠️

Common Pitfalls

Common mistakes when increasing memory limit include:

  • Trying to set memory limit in ini_set() when memory_limit is disabled in php.ini.
  • Using incorrect syntax or units (e.g., missing 'M' for megabytes).
  • Changing .htaccess on servers that do not allow overriding PHP settings.
  • Not restarting the web server after changing php.ini.
php
<?php
// Wrong: missing unit
ini_set('memory_limit', '256'); // This may not work as expected

// Right:
ini_set('memory_limit', '256M');
📊

Quick Reference

Summary of ways to increase PHP memory limit:

MethodUsageNotes
php.inimemory_limit = 256MRequires server access and restart
ini_set() in PHPini_set('memory_limit', '256M');Works if allowed by server settings
.htaccessphp_value memory_limit 256MOnly on Apache with PHP as module

Key Takeaways

Increase memory limit by setting memory_limit in php.ini or using ini_set() in scripts.
Always specify units like 'M' for megabytes when setting memory limits.
Restart your web server after changing php.ini for changes to take effect.
Check server permissions before using .htaccess to change PHP settings.
Use ini_get('memory_limit') to verify the current memory limit in your script.