Bartosz Górski Bartosz Górski - 3 months ago 15
Apache Configuration Question

.htaccess increase PHP memory limit ONLY if global is lower

I know there's a way to set PHP memory limit in the

.htaccess
file doing it this way:

<IfModule mod_php5.c>
php_value memory_limit 1024M
</IfModule>


or using
mod_php7.c
instead of
mod_php5.c
there, if running PHP7, not PHP5.

But is there a way (some conditional directive) to do that ONLY if the original
memory_limit
set in the global configuration is lower than the
.htaccess
value? I.e. make sure that the entry in the
.htaccess
file always increases, not decreases the limit?

Answer

No, that is not (directly) possible. However, what you can do is auto_prepend a PHP file that does what you want. You can specify this file in your .htaccess file and it will be prepended to any PHP file:

raise_memory_limit.php:

// return_bytes() function directly taken from http://php.net/ini_get
function return_bytes($val) {
  $val = trim($val);
  $last = strtolower($val[strlen($val)-1]);
  switch($last) {
      // The 'G' modifier is available since PHP 5.1.0
      case 'g':
          $val *= 1024;
      case 'm':
          $val *= 1024;
      case 'k':
          $val *= 1024;
  }

  return $val;
}

if (return_bytes(ini_get('memory_limit')) < 1024 * 1024 * 1024) {
    ini_set('memory_limit', '1024M');
}

.htaccess:

php_value auto_prepend_file "./raise_memory_limit.php"

This way, you don't have to touch any of your PHP files, and still are able to execute PHP code before your application runs. Note that any global variables and functions you specifiy here will be available in all your PHP files, so watch out for that.

Comments