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
NombrePor defectoCambiableHistorial de cambios
opcache.enable"1"INI_ALL 
opcache.enable_cli"0"INI_SYSTEMEntre 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_SYSTEMAntes 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_SYSTEMEliminado en PHP 7.2.0.
opcache.enable_file_override"0"INI_SYSTEM 
opcache.optimization_level"0x7FFFBFFF"INI_SYSTEMCambiado desde 0xFFFFFFFF en PHP 5.6.18
opcache.inherited_hack"1"INI_SYSTEMEliminado 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_SYSTEMDisponible a partir de PHP 8.0.0
opcache.preferred_memory_model""INI_SYSTEM 
opcache.protect_memory"0"INI_SYSTEM 
opcache.mmap_basenullINI_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_SYSTEMDisponible a partir de PHP 7.1.0
opcache.file_cacheNULLINI_SYSTEM 
opcache.file_cache_only"0"INI_SYSTEM 
opcache.file_cache_consistency_checks"1"INI_SYSTEM 
opcache.file_cache_fallback"1"INI_SYSTEMSolo Windows.
opcache.validate_permission"0"INI_SYSTEMDisponible a partir de PHP 7.0.14
opcache.validate_root"0"INI_SYSTEMDisponible a partir de PHP 7.0.14
opcache.preload""INI_SYSTEMDisponible a partir de PHP 7.4.0
opcache.preload_user""INI_SYSTEMDisponible a partir de PHP 7.4.0
opcache.cache_id""INI_SYSTEMSolo Windows. Disponible a partir de PHP 7.4.0
opcache.jit"tracing"INI_ALLDisponible a partir de PHP 8.0.0
opcache.jit_buffer_size"0"INI_SYSTEMDisponible a partir de PHP 8.0.0
opcache.jit_debug"0"INI_ALLDisponible a partir de PHP 8.0.0
opcache.jit_bisect_limit"0"INI_ALLDisponible a partir de PHP 8.0.0
opcache.jit_prof_threshold"0.005"INI_ALLDisponible a partir de PHP 8.0.0
opcache.jit_max_root_traces"1024"INI_SYSTEMDisponible a partir PHP 8.0.0
opcache.jit_max_side_traces"128"INI_SYSTEMDisponible a partir de PHP 8.0.0
opcache.jit_max_exit_counters"8192"INI_SYSTEMDisponible a partir de PHP 8.0.0
opcache.jit_hot_loop"64"INI_SYSTEMDisponible a partir de PHP 8.0.0
opcache.jit_hot_func"127"INI_SYSTEMDisponible a partir de PHP 8.0.0
opcache.jit_hot_return"8"INI_SYSTEMDisponible a partir de PHP 8.0.0
opcache.jit_hot_side_exit"8"INI_SYSTEMDisponible a partir de PHP 8.0.0
opcache.jit_blacklist_root_trace"16"INI_ALLDisponible a partir de PHP 8.0.0
opcache.jit_blacklist_side_trace"8"INI_ALLDisponible a partir de PHP 8.0.0
opcache.jit_max_loop_unrolls"8"INI_ALLDisponible a partir de PHP 8.0.0
opcache.jit_max_recursive_calls"2"INI_ALLDisponible a partir de PHP 8.0.0
opcache.jit_max_recursive_returns"2"INI_ALLDisponible a partir de PHP 8.0.0
opcache.jit_max_polymorphic_calls"2"INI_ALLDisponible 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.enableboolean

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_cliboolean

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

opcache.memory_consumptioninteger

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

opcache.interned_strings_bufferinteger

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_filesinteger

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_percentageinteger

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

opcache.use_cwdboolean

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_timestampsboolean

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_freqinteger

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_pathboolean

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_commentsboolean

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_commentsboolean

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_shutdownboolean

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_overrideboolean

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_levelinteger

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

opcache.inherited_hackbool

Esta directiva de configuración es ignorada.

opcache.dups_fixboolean

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

opcache.blacklist_filenamestring

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_sizeinteger

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_checksinteger

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_timeoutinteger

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_logstring

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_levelinteger

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_warningsbool

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_modelstring

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_memoryboolean

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

opcache.mmap_basestring

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_apistring

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_protectionstring

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_pagesstring

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_pathstring

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

opcache.opt_debug_levelstring

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_cachestring

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_onlyboolean

Habilita o inhabilita el almacenamiento de opcodes en memoria compartida.

opcache.file_cache_consistency_checksboolean

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

opcache.file_cache_fallbackboolean

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_permissionboolean

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

opcache.validate_rootboolean

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.preloadstring

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_userstring

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_idstring

On Windows, all processes running the same PHPSAPI 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.jitstring|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_sizeint

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_debugint

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

opcache.jit_bisect_limitint

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_thresholdfloat

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_tracesint

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_tracesint

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_countersint

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_loopint

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_funcint

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_returnint

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_exitint

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_traceint

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

opcache.jit_blacklist_side_traceint

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

opcache.jit_max_loop_unrollsint

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_callsint

Maximum number of unrolled recursive call loops.

opcache.jit_max_recursive_returnsint

Maximum number of unrolled recursive return loops.

opcache.jit_max_polymorphic_callsint

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

To Top