Configuración en tiempo de ejecución

El comportamiento de estas funciones se ve afectado por la configuración de php.ini.

Opciones de configuración de OPcache
Nombre Por defecto Cambiable Historial de cambios
opcache.enable "1" INI_ALL  
opcache.enable_cli "0" INI_SYSTEM Entre PHP 7.1.2 y 7.1.6 inclusive, el valor predetermindao era "1"
opcache.memory_consumption "128" INI_SYSTEM  
opcache.interned_strings_buffer "8" INI_SYSTEM  
opcache.max_accelerated_files "10000" INI_SYSTEM Antes de PHP 7.0.0 el valor predeterminado era "2000"
opcache.max_wasted_percentage "5" INI_SYSTEM  
opcache.use_cwd "1" INI_SYSTEM  
opcache.validate_timestamps "1" INI_ALL  
opcache.revalidate_freq "2" INI_ALL  
opcache.revalidate_path "0" INI_ALL  
opcache.save_comments "1" INI_SYSTEM  
opcache.fast_shutdown "0" INI_SYSTEM Eliminado en PHP 7.2.0.
opcache.enable_file_override "0" INI_SYSTEM  
opcache.optimization_level "0x7FFFBFFF" INI_SYSTEM Cambiado desde 0xFFFFFFFF en PHP 5.6.18
opcache.inherited_hack "1" INI_SYSTEM Eliminado en PHP 7.3.0.
opcache.dups_fix "0" INI_ALL  
opcache.blacklist_filename "" INI_SYSTEM  
opcache.max_file_size "0" INI_SYSTEM  
opcache.consistency_checks "0" INI_ALL  
opcache.force_restart_timeout "180" INI_SYSTEM  
opcache.error_log "" INI_SYSTEM  
opcache.log_verbosity_level "1" INI_SYSTEM  
opcache.record_warnings "0" INI_SYSTEM Disponible a partir de PHP 8.0.0
opcache.preferred_memory_model "" INI_SYSTEM  
opcache.protect_memory "0" INI_SYSTEM  
opcache.mmap_base null INI_SYSTEM  
opcache.restrict_api "" INI_SYSTEM  
opcache.file_update_protection "2" INI_ALL  
opcache.huge_code_pages "0" INI_SYSTEM  
opcache.lockfile_path "/tmp" INI_SYSTEM  
opcache.opt_debug_level "0" INI_SYSTEM Disponible a partir de PHP 7.1.0
opcache.file_cache NULL INI_SYSTEM  
opcache.file_cache_only "0" INI_SYSTEM  
opcache.file_cache_consistency_checks "1" INI_SYSTEM  
opcache.file_cache_fallback "1" INI_SYSTEM Solo Windows.
opcache.validate_permission "0" INI_SYSTEM Disponible a partir de PHP 7.0.14
opcache.validate_root "0" INI_SYSTEM Disponible a partir de PHP 7.0.14
opcache.preload "" INI_SYSTEM Disponible a partir de PHP 7.4.0
opcache.preload_user "" INI_SYSTEM Disponible a partir de PHP 7.4.0
opcache.cache_id "" INI_SYSTEM Solo Windows. Disponible a partir de PHP 7.4.0
opcache.jit "tracing" INI_ALL Disponible a partir de PHP 8.0.0
opcache.jit_buffer_size "0" INI_SYSTEM Disponible a partir de PHP 8.0.0
opcache.jit_debug "0" INI_ALL Disponible a partir de PHP 8.0.0
opcache.jit_bisect_limit "0" INI_ALL Disponible a partir de PHP 8.0.0
opcache.jit_prof_threshold "0.005" INI_ALL Disponible a partir de PHP 8.0.0
opcache.jit_max_root_traces "1024" INI_SYSTEM Disponible a partir PHP 8.0.0
opcache.jit_max_side_traces "128" INI_SYSTEM Disponible a partir de PHP 8.0.0
opcache.jit_max_exit_counters "8192" INI_SYSTEM Disponible a partir de PHP 8.0.0
opcache.jit_hot_loop "64" INI_SYSTEM Disponible a partir de PHP 8.0.0
opcache.jit_hot_func "127" INI_SYSTEM Disponible a partir de PHP 8.0.0
opcache.jit_hot_return "8" INI_SYSTEM Disponible a partir de PHP 8.0.0
opcache.jit_hot_side_exit "8" INI_SYSTEM Disponible a partir de PHP 8.0.0
opcache.jit_blacklist_root_trace "16" INI_ALL Disponible a partir de PHP 8.0.0
opcache.jit_blacklist_side_trace "8" INI_ALL Disponible a partir de PHP 8.0.0
opcache.jit_max_loop_unrolls "8" INI_ALL Disponible a partir de PHP 8.0.0
opcache.jit_max_recursive_calls "2" INI_ALL Disponible a partir de PHP 8.0.0
opcache.jit_max_recursive_returns "2" INI_ALL Disponible a partir de PHP 8.0.0
opcache.jit_max_polymorphic_calls "2" INI_ALL Disponible a partir de PHP 8.0.0
Para más detalles y definiciones de los modos de INI_*, vea Dónde se puede realizar un ajuste de configuración.

He aquí una breve explicación de las directivas de configuración.

opcache.enable boolean

Habilita la caché de opcode. Cuando está deshabilitado, el código no es optimizado o almacenado en caché. El ajuste opcache.enable no puede ser habilitado en tiempo de ejecución enabled at runtime a través de ini_set(), solamente puede ser deshabilitado. Intentar habilitarlo en un script gernerará una advertencia.

opcache.enable_cli boolean

Habilita la caché de opcode para la versión CLI de PHP.

opcache.memory_consumption integer

EL tamaño del almacén de memoria compartida utilizado por OPcache, en megabytes.

opcache.interned_strings_buffer integer

La cantidad de memoria utilizada para almacenar cadenas, en megabytes. Esta directiva de configuración es ignorada en PHP < 5.3.0.

opcache.max_accelerated_files integer

El número máximo de claves (y por lo tanto, de scripts) en la tabla de hash de OPcache. El valor que realmente se utilizará será el primer número en el conjunto de los números primos { 223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987 } que sea mayor o igual al valor configurado. El valor mínimo es 200. El valor máximo es 100000 en PHP < 5.5.6, y 1000000 en versiones posteriores.

opcache.max_wasted_percentage integer

El porcentaje máximo de memoria desperdiciada que está permitida antes de que un reinicio sea programado.

opcache.use_cwd boolean

Si está habilitada, OPcache añade el directorio de trabajo actual a la clave del script, eliminado así las posibles colisiones entre ficheros con el mismo nombre base. Deshabilitar esta directiva mejora el rendimiento pero podría generar problemas en aplicaciones existentes.

opcache.validate_timestamps boolean

Si está habilitado, OPcache consultará por scripts actualizados cada opcache.revalidate_freq segundos. Cuando esta directiva está deshabilitada, se debe reiniciar OPcache de forma manual mediante opcache_reset(), opcache_invalidate() o reiniciando el servidor web para que los cambios en el sistema de ficheros tomen efecto.

opcache.revalidate_freq integer

La frecuencia de verificación de las marcas temporales de Unix de los scripts por actualizaciones, en segundos. 0 hará que OPcache consulte por actualizaciones en cada petición.

Esta directiva de configuración es ignorada si opcache.validate_timestamps está deshabilitada.

opcache.revalidate_path boolean

Si está deshabilitada, los ficheros cacheados existentes que usen el mismo include_path serán reutilizados. Por lo tanto, si un fichero con el mismo nombre está en algún otro lado del include_path, no será encontrado.

opcache.save_comments boolean

Si está deshabilitada, todos los comentarios de la documentación serán elliminados de la caché de opcode para reducir el tamaño del código optimizado. Deshabilitar esta directiva de configuración podría generar problemas en aplicaciones y frameworks que dependen del análisis de comentarios para anotaciones, incluyendo Doctrine, Zend Framework 2 y PHPUnit.

opcache.load_comments boolean

Si está deshabilitada, los comentarios de la documentación no serán cargados de la caché de opcode aun si éstos existen. Esto puede ser usado junto con opcache.save_comments para cargar sólo los comentarios para las aplicaciones que los requieran.

opcache.fast_shutdown boolean

Si está habilitada, una secuencia de apagado rápida es utilizada que no libera cada bloque asignado sino que depende del gestor de memoria del Zend Engine para rescindir del conjunto de variables de petición completo.

Esta directiva ha sido eliminada en PHP 7.2.0. Se ha integrado una variante de la secuencia de apagado rápido en PHP, y será usada automáticamente si es posible.

opcache.enable_file_override boolean

Cuando está habilitada, la caché de opcode será consultado para determinar si un fichero ya ha sido cacheado cuando file_exists(), is_file() y is_readable() son llamadas. Esto puede incrementar el rendimiento en aplicaciones que chequean la existencia y legibilidad de los scripts PHP, pero arriesgando devolver datos obsoletos si opcache.validate_timestamps está deshabilitada.

opcache.optimization_level integer

Un bitmask que controla cúales permisos de optimización son ejecutados.

opcache.inherited_hack bool

Esta directiva de configuración es ignorada.

opcache.dups_fix boolean

Este hack debería estar habilitado para funcionar sólo para evitar errores "Cannot redeclare class".

opcache.blacklist_filename string

La ubicación del fichero de blacklist de OPcache. Un fichero blacklist es un texto que contiene los nombres de los ficheros que no deberían ser acelerados, uno por línea. Se permiten comodines, y prefijos también pueden ser provistos. Las líneas que comienzen con un punto y coma son ignoradas como comentarios.

Un fichero blacklist simple luciría así:

; Matches a specific file.
/var/www/broken.php
; A prefix that matches all files starting with x.
/var/www/x
; A wildcard match.
/var/www/*-broken.php
opcache.max_file_size integer

El tamaño de fichero máximo que será almacenado en caché, en bytes. Si es 0, todos los ficheros serán almacenados en caché.

opcache.consistency_checks integer

Si es distinto de cero, OPcache verificará el checksum de la caché cada N peticiones, donde N es el valor de esta directiva de configuración. Esto debería sólo estar habilitado durante la depuración ya que puede tener un impacto negativo en el rendimiento.

opcache.force_restart_timeout integer

La cantidad de tiempo a esperar el comienzo de un reinicio programado si la caché no está activa, en segundos. Si se acaba el tiempo, entonces OPcache asume que algo anda mal y terminará todos los procesos que bloqueen la caché para permitir un reinicio.

Si opcache.log_verbosity_level es 2 o más, una advertencia será guardada en el registro de errores si esto ocurre.

opcache.error_log string

El registro de errores de errores de OPcache. Una cadena vacía es tratada de igual forma que stderr, y resultará en registros siendo enviados a errores estándar (que será el registro de errores del servidor Web en la mayoría de los casos).

opcache.log_verbosity_level integer

El nivel de verbosidad del registro. Por defecto, sólo los errores fatales (nivel 0) y errores (nivel 1) son registrados. Otros niveles disponibles son advertencias (nivel 2), mensajes de información (nivel 3) y mensajes de depuración (nivel 4).

opcache.record_warnings bool

If enabled, OPcache will record compile-time warnings and replay them on the next include, even if it is served from cache.

opcache.preferred_memory_model string

El modelo de memoria principal que utilizará OPcache. Si se deja vacío, OPcache seleccionará el modelo más apropiado, el cual es el comportamiento correcto en prácticamente todos los casos.

Los valores posibles incluyen mmap, shm, posix y win32.

opcache.protect_memory boolean

Protege la memoria compartida de escrituras inesperadas mientras se ejecutan scripts. Esto es útil sólo para depuración interna.

opcache.mmap_base string

La base usada para los segmentos de memoria compartida en Windows. Todos los procesos PHP deben mapear la memoria compartida con el mismo espacio de direcciones. Utilizando esta directiva se corrigen los errores "Unable to reattach to base address".

opcache.restrict_api string

Permite llamar a funciones de la API de OPcache solamente desde scripts de PHP cuya ruta comience con la cadena especificada. El valor predeterminado de "" significa sin restricciones.

opcache.file_update_protection string

Previene de almacenar en caché ficheros que estén menos que este número de segundos. Protege del almacenamiento en caché de ficheros no actualizados completamente. En caso de que todas las actualizaciones de ficheros del sitio sean atómicas, se puede aumentar el rendimiento estableciéndolo a "0".

opcache.huge_code_pages string

Habilita o inhabilita la copia de código de PHP (segmento de texto) a HUGE PAGES. Esto debería mejorar el rendimiento, aunque requiere una configuración apropiada del SO.

opcache.lockfile_path string

Ruta absoluta usada para almacenar shared lockfiles compartidos (solo para *nix)

opcache.opt_debug_level string

Produce volcados de opcode para depurar diferentes escenarios de optimización. 0x10000 generará opcodes a medida que el compilador los haya producido antes de ocurra cualquier optimización, mientras que 0x20000 generará códigos optimizados.

opcache.file_cache string

Habilita y establece el segundo nivel de directorio de caché. Debería mejorar el rendimiento cuando la memoria SHM esté llena, cuando se reinicie el servidor o se restablezca la SHM. El valor predeterminado "" inhabilita el almacenamiento en cache basado en ficheros.

opcache.file_cache_only boolean

Habilita o inhabilita el almacenamiento de opcodes en memoria compartida.

opcache.file_cache_consistency_checks boolean

Habilita o inhabilita la validación del checksum cuando un script sea cargado desde la caché de ficheros.

opcache.file_cache_fallback boolean

Implica opcache.file_cache_only=1 para ciertos procesos que fallan al volver a vincularse a la memoria conpartida (solo Windows). Es necesaria la caché de ficheros explícitamente.

Precaución

La inhabilitación de esta opción de configuración puede evitar el inicio de procesos, por lo que está desaconsejado.

opcache.validate_permission boolean

Valida los permisos de ficheros almacenados en caché con el usuario en uso.

opcache.validate_root boolean

Evita la colisión de nombres en entornos con chroot. Debe estar habilitado en todos los entornos con chroot para evitar el acceso a ficheros fuera de chroot.

opcache.preload string

Especifica un script de PHP que va a ser compilado y ejecutado en el arranque del servidor, lo que podría precargar otros ficheros, ya sea con include o usando la función opcache_compile_file(). Todas las entidades (p. ej. funciones y clases) definidas en estos ficheros estarán disponibles para peticiones listas para usar, hasta que el servidor sea apagado.

opcache.preload_user string

La precarga de código como «root» no está permitida por razones de seguridad. Esta directiva facilita que la precarga se ejecute como otro usuario.

opcache.cache_id string

On Windows, all processes running the same PHP SAPI under the same user account having the same cache ID share a single OPcache instance. The value of the cache ID can be freely chosen.

Sugerencia

For IIS, different application pools can have their own OPcache instance by using the environment variable APP_POOL_ID as opcache.cache_id.

opcache.jit string|int

For typical usage, this option accepts one of four string values:

  • disable: Completely disabled, cannot be enabled at runtime.
  • off: Disabled, but can be enabled at runtime.
  • tracing/on: Use tracing JIT. Enabled by default and recommended for most users.
  • function: Use function JIT.

For advanced usage, this option accepts a 4-digit integer CRTO, where the digits mean:

C (CPU-specific optimization flags)
  • 0: Disable CPU-specific optimization.
  • 1: Enable use of AVX, if the CPU supports it.
R (register allocation)
  • 0: Don't perform register allocation.
  • 1: Perform block-local register allocation.
  • 2: Perform global register allocation.
T (trigger)
  • 0: Compile all functions on script load.
  • 1: Compile functions on first execution.
  • 2: Profile functions on first request and compile the hottest functions afterwards.
  • 3: Profile on the fly and compile hot functions.
  • 4: Currently unused.
  • 5: Use tracing JIT. Profile on the fly and compile traces for hot code segments.
O (optimization level)
  • 0: No JIT.
  • 1: Minimal JIT (call standard VM handlers).
  • 2: Inline VM handlers.
  • 3: Use type inference.
  • 4: Use call graph.
  • 5: Optimize whole script.
The "tracing" mode corresponds to CRTO = 1254, the "function" mode corresponds to CRTO = 1205.

opcache.jit_buffer_size int

The amount of shared memory to reserve for compiled JIT code. A zero value disables the JIT.

Cuando se usa un integer, el valor del mismo es medido en bytes. También se puede usar la notación reducida, tal como se describe en esta FAQ.
opcache.jit_debug int

A bit mask specifying which JIT debug output to enable. For possible values, please consult zend_jit.h.

opcache.jit_bisect_limit int

Debugging option that disables JIT compilation after compiling a certain number of functions. This may be helpful to bisect the source of a JIT miscompilation. Note: this option only works when JIT trigger is set to 0 (compile on script load) or 1 (compile on first execution), e.g., opcache.jit=1215. See more in opcache.jit option.

opcache.jit_prof_threshold float

When using the "profile on first request" trigger mode, this threshold determines whether a function is considered hot. The number of calls to the function divided by the number of calls to all functions must be above the threshold. For example, a threshold of 0.005 means that functions that made up more than 0.5% of all calls will be JIT compiled.

opcache.jit_max_root_traces int

Maximum number of root traces. The root trace is an execution flow taking one path through the code firstly, which is a unit of JIT compilation. JIT will not compile new code if it reaches this limit.

opcache.jit_max_side_traces int

Maximum number of side traces a root trace may have. The side trace is another execution flow that does not follow the path of compiled root trace. Side traces belonging to the same root trace will not be compiled if it reaches this limit.

opcache.jit_max_exit_counters int

Maximum number of side trace exit counters. This limits the total number of side traces there may be, across all root traces.

opcache.jit_hot_loop int

After how many iterations a loop is considered hot. Valid value range is [0,255]; for any setting out of this range, e.g., -1 or 256, default value will be used instead. Specially, a zero value will disable JIT to trace and compile any loops.

opcache.jit_hot_func int

After how many calls a function is considered hot. Valid value range is [0,255]; for any setting out of this range, e.g., -1 or 256, default value will be used instead. Specially, a zero value will disable JIT to trace and compile any functions.

opcache.jit_hot_return int

After how many returns a return is considered hot. Valid value range is [0,255]; for any setting out of this range, e.g., -1 or 256, default value will be used instead. Specially, a zero value will disable JIT to trace and compile any returns.

opcache.jit_hot_side_exit int

After how many exits a side exit is considered hot. Valid value range is [0,255]; for any setting out of this range, e.g., -1 or 256, default value will be used instead. Specially, a zero value will disable JIT to trace and compile any side exits.

opcache.jit_blacklist_root_trace int

Maximum number of times the compilation of a root trace is attempted before it is blacklisted.

opcache.jit_blacklist_side_trace int

Maximum number of times the compilation of a side trace is attempted before it is blacklisted.

opcache.jit_max_loop_unrolls int

Maximum number of attempts to unroll a loop in a side trace, trying to reach the root trace and close the outer loop.

opcache.jit_max_recursive_calls int

Maximum number of unrolled recursive call loops.

opcache.jit_max_recursive_returns int

Maximum number of unrolled recursive return loops.

opcache.jit_max_polymorphic_calls int

Maximum number of attempts to inline polymorphic (dynamic or method) calls. Calls above this limit are treated as megamorphic and are not inlined.

add a note add a note

User Contributed Notes 6 notes

up
7
wessos at example dot org
5 years ago
The optimization levels as of php 7.3 are the following:

#define ZEND_OPTIMIZER_PASS_1        (1<<0)   /* CSE, STRING construction     */
#define ZEND_OPTIMIZER_PASS_2        (1<<1)   /* Constant conversion and jumps */
#define ZEND_OPTIMIZER_PASS_3        (1<<2)   /* ++, +=, series of jumps      */
#define ZEND_OPTIMIZER_PASS_4        (1<<3)   /* INIT_FCALL_BY_NAME -> DO_FCALL */
#define ZEND_OPTIMIZER_PASS_5        (1<<4)   /* CFG based optimization       */
#define ZEND_OPTIMIZER_PASS_6        (1<<5)   /* DFA based optimization       */
#define ZEND_OPTIMIZER_PASS_7        (1<<6)   /* CALL GRAPH optimization      */
#define ZEND_OPTIMIZER_PASS_8        (1<<7)   /* SCCP (constant propagation)  */
#define ZEND_OPTIMIZER_PASS_9        (1<<8)   /* TMP VAR usage                */
#define ZEND_OPTIMIZER_PASS_10        (1<<9)   /* NOP removal                 */
#define ZEND_OPTIMIZER_PASS_11        (1<<10)  /* Merge equal constants       */
#define ZEND_OPTIMIZER_PASS_12        (1<<11)  /* Adjust used stack           */
#define ZEND_OPTIMIZER_PASS_13        (1<<12)  /* Remove unused variables     */
#define ZEND_OPTIMIZER_PASS_14        (1<<13)  /* DCE (dead code elimination) */
#define ZEND_OPTIMIZER_PASS_15        (1<<14)  /* (unsafe) Collect constants */
#define ZEND_OPTIMIZER_PASS_16        (1<<15)  /* Inline functions */

Source: https://lxr.room11.org/xref/php-src%40master/ext/opcache/Optimizer/zend_optimizer.h
up
9
damien at overeem dot org
7 years ago
When using PHP on a windows platform and enabling opcache, you might run into occasional 500 errors. These will appear to show up entirely random.

When this happens, your windows Event log (Windows Logs/Application) will show (probably multiple)  entries from Zend OPcache with Event ID 487. Further information will state the following error message: "Base address marks unusable memory region".

This issue can be resolved by adding the following to your php.ini:

    opcache.mmap_base = 0x20000000

Unfortunately I do not know the significance of the value "0x20000000". I can only tell you that this value works to solve the problem (Tried and tested)
up
4
tizian dot schmidlin at gmail dot com
5 years ago
It should be noted that according to the original RFC (https://wiki.php.net/rfc/preload) `opcache.preload` caches preloaded files *forever* for all instances of the underlying PHP process.

That means, that hosting multiple websites on the same server might result in some unexpected behaviour.

Concrete example:
- you have a Symfony 3.2 App (which might be an endpoint of some type) and a Symfony 3.4 App (which might be your main application)
- both apps have a main Class called App that is in the same namespace (as it is usual, since the class name is unique to each project)
- depending on which app is loaded first, one or the other will work, since `opcache.preload` has no file based distinction of what class is used where and simply provides them to the user space

This is avoidable by simply not preloading user space classes or, if you work with FPM, by defining a pool for each app.

In order to optimize memory consumption, you might also use a common FPM Pool for all Symfony 3.4 Apps and preload the entire framework in there and simply not preload user space classes (which might be cached by opcache anyway but is slower, since it will be checked if the file has changed on every request).
up
2
carneiro at isharelife dot com dot br
4 years ago
If you try to allocate more memory that is available using opcache.memory_consumption PHP stops working without any logs to help on debugging. This issue took me 4 hours to solve when creating a staging server with same configrations and less memory that was available on production server.
up
3
bdurand at ensemblegroup dot net
7 years ago
It would appear as though the [opcache.enable] setting is indeed NOT PHP_INI_ALL.
For changing it within user.ini yields no effect when disabled at global level. user.ini is ignored for that setting.
up
-14
BR
8 years ago
opcache.max_wasted_percentage must have a value between 1 and 50. Otherwise it will automatically set the variable 5 %.
To Top