Php ini enable opcache

Настройка PHP OPcache для оптимизация работы сайта

Zend OPcache — PHP-акселератор, обеспечивает ускорение выполнения PHP кода благодаря кэшированию и оптимизации, сохраняет скомпилированный байт-код в разделяемой памяти.

Opcache позволяет значительно ускорить скорость генерации страниц.

OPcache включен по умолчанию начиная с PHP 5.5

Создадим файл конфигурации OPcache:

echo > /etc/php.d/10-opcache.ini

и добавим в него конфиг (пример конфигурации)

Не стоит использовать готовые конфигурации найденные в интернете. Это может привести к остановке работы сайта. Подбирайте индивидуально.

zend_extension=opcache.so opcache.enable=1 opcache.memory_consumption=512 opcache.interned_strings_buffer=32 opcache.max_accelerated_files=130987 opcache.max_wasted_percentage=5 opcache.use_cwd=1 opcache.validate_timestamps=1 opcache.revalidate_path=1 opcache.enable_file_override=1 opcache.fast_shutdown=1 opcache.save_comments=1 opcache.load_comments=1

После чего необходимо перезапустить веб сервер, в данном случае apache

Включить JIT в PHP 8

Компилятор JIT (Just In Time) в PHP 8 реализован как часть расширения Opcache и призван компилировать операционный код в инструкции процессора в реальном времени. Что позволяет еще больше повысить производительность.

Для включения необходимо указать размер буфера opcache.jit_buffer_size, по умолчанию 0.

Добовляем в наш файл /etc/php.d/10-opcache.ini строку:

opcache.jit_buffer_size=128M

и перезапускаем веб сервер, это все что требуется.

Опции OPcache

Опция По молчанию Описание
opcache.enable 1 включение/выключение OPcache
opcache.enable_cli 0 включение OPcache при вызове PHP из командной строки
opcache.memory_consumption 64 размер используемой памяти (в мб.) для хранения прекомпилированного PHP-кода
opcache.interned_strings_buffer 4 количество памяти для пула строк в мегабайтах
opcache.max_accelerated_files 2000 максимальное количество ключей в хэш-таблице OPcache, допустимы значения между 200 и 1000000
opcache.max_wasted_percentage 5 максимальный процент замусоренной памяти для запланированного перезапуска
opcache.use_cwd 1 при включении добавляет текущую рабочую директорию в ключ скрипта для предотвращения возникновения колизий между файлами с одинаковым именем
opcache.validate_timestamps 1 возможность обнуления OPcache вручную или перезапуском веб-сервера для того, чтобы привести в актуальное состояние данных об изменениях в файлах
opcache.revalidate_freq 2 через какой промежуток времени (в секундах) проверять изменения временных меток для поддержания данных в памяти в актуальном состоянии, где 1 — проверка с периодичностью раз в секунду, 0 — постоянная проверка.
opcache.file_update_protection 2 предотвращает кэширование файлов, которые были изменены меньше, чем в указанное время (в секундах)
opcache.revalidate_path включение или отключение оптимизации поиска файлов в include_path
opcache.save_comments 1 если выключено, все комментарии PHPDoc будут удалены из кода с целью уменьшения размера оптимизированного кода.
opcache.load_comments 1 если выключено, то комментарии PHPDoc не будут загружаться из общей памяти
opcache.fast_shutdown 0 если включено, будет использоваться последовательность быстрых выключений для оптимизированного кода
opcache.enable_file_override 0 при включении OPcache будет проверять наличие закэшированного файла при вызовах file_exists(), is_file() и is_readable()
opcache.optimization_level 0xffffffff битовая маска, в которой каждый бит включает или отключает в соответствующие проходы OPcache
opcache.inherited_hack 1 включение этого хака при ошибках вида can’t redeclare class
opcache.dups_fix 0 Необходимо включить при появлении ошибок вида Can’t redeclare class
opcache.blacklist_filename месторасположение списка файлов, к которым запрещен доступ для OPcache
opcache.max_file_size 0 указывает максимальный размер файла для кеширования, позволяет исключать большие файлы
opcache.consistency_checks 0 проверять контрольную сумму кэша каждое N-ое количество запросов, подсчет контрольной суммы снижает производительность
opcache.force_restart_timeout 180 время ожидания (в секундах) перед перезагрузкой в случае недоступности кэша
opcache.error_log определение названия и местоположения лога ошибок OPcache
opcache.log_verbosity_level 1 все ошибки OPcache отправляет в лог-файл веб-сервера. По умолчанию логируются только критические ошибки (0) и обычные ошибки (1).
  • disable — Полностью отключён, не может быть включён во время выполнения.
  • off — Отключено, но может быть включено во время выполнения.
  • tracing — Используйте трассировку JIT. Включено по умолчанию и рекомендуется для большинства пользователей.
  • function — Использование функции JIT.

Похожие записи:

Источник

Php ini enable opcache

PHP as a language is an interpreted. But the interpretation happens from the binaries. These binaries are compiled into intermediate bytecodes. OPcache comes into picture during the compilation phase where it stores the precompiled script’s bytecodes into a shared memory. When next time PHP needs to compile the same PHP script, the precompile bytecodes from the shared memory are used.. Therefore removing the requirement for PHP to load and parse scripts on each request. As a result improving overall PHP performance.

The OPcache extension is bundled with PHP 5.5.0 and later versions.

Why it is needed :

Okay wait. Let’s really get into a very vital need of this OPcache in the ever growing world of PHP frameworks. Any PHP framework has some core package files which we never change. These php package files really let us use the framework capabilities. For example for laravel, we have illuminate ‘s laraval packages. Now on top of that, we install new PHP packages as and when needed using dependency managers like composer . We hardly change these files unless we update/install/remove a package dependency.

Now, independent of which PHP framework you are using, these core PHP script files which constitute framework more or less are compiled for each request to generate their bytecodes for interpretation. Similarly, the dependency package PHP script are compied as per their need for that particular request.

Why do we really need to compile these core PHP script files which we indeed hardly change?? Isn’t that an overly unneccessary overhead for PHP compilation process to compile these hundreds of PHP script files on each request and thenm intrepret them? Doesn’t make much sense right? There you go.. OPcache to the rescue.

Important settings of OPcache :

As OPcache overall sounds really fascinating which internally optimizes the compilation process of PHP scripts, it is equally important to know the important settings. Cache handling, cache clearing and cache storing and overall invalidation depends on these settings.

  • Finding the php.ini to work with : You need to find the php.ini which is currently in use. There are different ways to find it. You can find it from terminal using :

OR create a temporary script file called ‘info.php` and have following content on it :

Once you open this file into browser, you would be able to see which php.ini is used.

Mostly if you have php version 7.x with fpm installed then it will be inside /etc/php/7.x/fpm/php.ini . Or if you have 7.x with apache2 installed then it will be inside /etc/php/7.x/apache2/php.ini .

    Enable opcache : In the loaded and used php.ini , you can enable and disable opcache by updating following directive :

opcache.enable=1 //Enables OPcache opcache.enable=0 //Disables OPcache 
opcache.enable_cli=1 //Enables OPcache opcache.enable_cli=0 //Disables OPcache 
opcache.memory_consumption=128 
# Make sure you change this path as per your setup cd /var/www/html # Count number of php files find . -type f -print | grep php | wc -l 

Now above will givbe you a numeric count of total PHP script files in your codebase. Now you can set OPcache setting accordingly. In the loaded and used php.ini , you can change this setting by updating following directive :

opcache.max_accelerated_files=20000 
opcache.validate_timestamps=1 //Enabled opcache.validate_timestamps=0 //Disabled 
opcache.revalidate_freq=120 
opcache.validate_timestamps=0 //Disables OPcache revalidation 
opcache.blacklist_filename=/etc/php/7.x/fpm/opcache_blacklist.txt 
#Specific file inside /var/www/html/ /var/www/html/user.php #All files starting with user* inside /var/www/html/ /var/www/html/user #Wildcare usage inside /var/www/html/ /var/www/*-user.php 
opcache.interned_strings_buffer=12 

Note that to have changes to take effect from php.ini, you need to restart PHP FPM or apache2 depending on your setup.

Clearing the OPcache :

When OPcache is enabled, any changes in cached PHP script files will not take effect until OPcache is cleared or it is revalidated. This is applicable when you release new updates into a OPcache enabled PHP server.

To clear cache there are multiple ways :

    Clearing from browser : You can have a file opcache_refresh.php with following content :

sudo service php7.x-fpm reload 
sudo service apache2 reload 
// Download the phar curl -sO http://gordalina.github.io/cachetool/downloads/cachetool.phar // Set permissions chmod +x cachetool.phar 
// Using an automatically guessed fastcgi server php cachetool.phar opcache:reset --fcgi // Using php fpm socket php cachetool.phar opcache:reset --fcgi=/var/run/php7.x-fpm.sock 

OPcache and the automated deployments :

When you have automated deployments set up on your PHP server, you need to incorporate OPcache clearing so that new changes take effect.

If you do not perform this manually, eventually OPcache will revalidate itself based on your OPcache revalidation settings assuming you have validate_timestamps set to 1 . But it is pretty handy to do it manually as part of your automated deployment scripts to make sure changes take immediate effect.

From my personal experience, relading FPM or apache2 to clear OPcache is not a good option. Even if it gracefully reloads PHP processes, any request which is(unfortunarely) ongoing on the server gives 502 bad gateway . I would rather use the alternative like cachetool mentioned in above section which does not affect any ongoing PHP processes at all.

The sequence when you reload OPcache matters. As soon as git or any of your deployment methods pulls the latest PHP code changes, you should first clear the OPcache. Then you can run all the remaining deployment commands which may use the updated PHP files. This makes sure the deployment commands do not use cached PHP script opcodes even when the sever has pulled the latest changes.

Источник

Читайте также:  Php dir to array
Оцените статью