====== PHP: APC opcache ======
APC крайне популярный даже в 2016 году [[https://ru.wikipedia.org/wiki/Акселератор_PHP|опкэш]].
{{:linux:php_apc_cache.png?nolink|}}
===== Установка =====
==== Centos 6 ====
# yum install php-pecl-apc
Версия в base репозитории
Name : php-pecl-apc
Arch : i686
Version : 3.1.9
Release : 2.el6
Size : 96 k
Repo : base
Summary : APC caches and optimizes PHP intermediate code
URL : http://pecl.php.net/package/APC
License : PHP
Description : APC is a free, open, and robust framework for caching and optimizing PHP
: intermediate code.
Версия в Atomic репозитории
Name : php-pecl-apc
Arch : i686
Version : 3.1.15
Release : 0.6.svn329913.el6.art
Size : 140 k
Repo : atomic
Summary : APC caches and optimizes PHP intermediate code
URL : http://pecl.php.net/package/APC
License : PHP
Description : APC is a free, open, and robust framework for caching and optimizing PHP
: intermediate code.
==== Debian 7 ====
# apt-get install php-apc
Если используется репозиторий dotdeb
# apt-get install php5-apc
==== pecl ====
APC можно установить и через [[https://pecl.php.net/package/APC|pecl]]
# pecl install apc
Но для этого нужно дополнительно ставить devel-пакеты, gcc и др.
# yum install httpd-devel gcc make php-devel php-pear pcre-devel
Иначе можно словить такую ошибку
/usr/include/php5/ext/pcre/php_pcre.h:29:18: fatal error: pcre.h: No such file or directory
compilation terminated.
make: *** [apc.lo] Error 1
ERROR: `make' failed
===== Конфигурационный файл apc.ini =====
Пример конфигурационного файла
[APC]
extension=apc.so
apc.enabled=1
;Only set to 1 while debugging
apc.enable_cli=0
apc.shm_segments=1
;32M per WordPress install
apc.shm_size=256M
;Relative to the number of cached files (you may need to watch your stats for a day or two to find out a good number)
apc.num_files_hint=7000
;Relative to the size of WordPress
apc.user_entries_hint=4096
;The number of seconds a cache entry is allowed to idle in a slot before APC dumps the cache
apc.ttl=7200
apc.user_ttl=7200
apc.gc_ttl=3600
;Setting this to 0 will give you the best performance, as APC will
;not have to check the IO for changes. However, you must clear
;the APC cache to recompile already cached files. If you are still
;developing, updating your site daily in WP-ADMIN, and running W3TC
;set this to 1
apc.stat=1
;This MUST be 0, WP can have errors otherwise!
apc.include_once_override=0
;Allow 2 seconds after a file is created before it is cached to prevent users from seeing half-written/weird pages
apc.file_update_protection=2
;Leave at 2M or lower. WordPress does't have any file sizes close to 2M
apc.max_file_size=2M
;Ignore files
apc.filters = "/var/www/apc.php"
apc.cache_by_default=1
apc.use_request_time=1
apc.slam_defense=0
apc.mmap_file_mask=/var/www/temp/apc.XXXXXX
apc.stat_ctime=0
apc.canonicalize=1
apc.write_lock=1
apc.report_autofilter=0
apc.rfc1867=0
apc.rfc1867_prefix =upload_
apc.rfc1867_name=APC_UPLOAD_PROGRESS
apc.rfc1867_freq=0
apc.rfc1867_ttl=3600
apc.lazy_classes=0
apc.lazy_functions=0
[[http://php.net/manual/ru/apc.configuration.php|Описание опций]] на сайте PHP.
===== Как отключить APC и включить только для некоторых сайтов =====
Отключаем APC по-умолчанию (''apc.ini'')
extension=apc.so
apc.enabled=1
apc.cache_by_default=0
Включаем на уровне виртуального хоста или через .htaccess файл.
php_flag apc.cache_by_default On
===== Веб-интерфейс =====
У APC есть встроенный админ-интерфейс. Для активации необходимо скопировать ''apc.php'' в желаемый каталог
==== CentOS ====
# cp apc.php /var/www/html/apc.php
==== Debian ====
# cp /usr/share/doc/php-apc/apc.php /var/www/html/apc.php
Но если для PHP вы используете репозиторий dotdeb, то файла apc.php у вас не будет. В каталоге ''/usr/share/doc/php5-apc/'' где казалось бы он должен быть только файл changelog.Debian.gz
# find / -type f -name apc.php*
/usr/share/phpmyadmin/libraries/import/upload/apc.php
''apc.php'' можно достать из .deb пакета - http://ftp.us.debian.org/debian/pool/main/p/php-apc/php-apc_3.1.13-1_amd64.deb
==== pecl ====
Если установка производилась через pecl, то ''apc.php'' должен быть в каталоге ''/usr/share/pear/apc.php''
==== Проверка ====
При попытке зайти по адресу http://foobar.com/apc.php
появится сообщение ''You need to set a password at the top of apc.php before this will work!''
Устанавливаем логин и пароль для доступа к APC
defaults('ADMIN_USERNAME','apc'); // Admin Username
defaults('ADMIN_PASSWORD','password'); // Admin Password - CHANGE THIS TO ENABLE!!!
Альтернативный админ интерфейс для APC
* https://github.com/jithinjose2/APC-Admin
* http://www.techzonemind.com/apc-admin-new-generation-admin-interface-php-apc/
===== Ошибки =====
==== PHP Startup: apc.shm_size now uses M/G suffixes ====
Ошибка **PHP Warning: PHP Startup: apc.shm_size now uses M/G suffixes, please update your ini files** решается просто
Необходимо указать размер кэша в мегабайтах "**M**" или гигабайтах "**G**"
Вместо
apc.shm_size=256
должно быть указано
apc.shm_size=256M
==== phpmyadmin не работает с APC ====
Ошибка
PHP Fatal error: Class 'PMA_Error_Handler' not found in .../phpMyAdmin/libraries/common.inc.php on line X
PHP Fatal error: Call to undefined function PMA_getenv() in .../phpMyAdmin/libraries/common.inc.php on line X
Отключаем через .htaccess (см. выше) или через виртуальный хост
php_admin_value apc.enabled 0
==== Unable to allocate memory for pool ====
http://jbzoo.ru/docs/apc-unable-to-allocate-memory-for-pool
===== Ссылки =====
Подробности работы опкэша, комментарии к настройкам, etc
* [[https://www.scalingphpbook.com/best-zend-opcache-settings-tuning-config/|Best Zend OpCache Settings/Tuning/Config]]
* [[http://www.vionblog.com/biggest-apc-configuration-mistake/|Biggest APC Configuration mistake]]
* [[http://gregrickaby.com/the-perfect-apc-configuration/|The Perfect APC Configuration]]
* [[http://serverfault.com/questions/403135/what-does-apc-mmap-file-mask-really-do|What does apc.mmap_file_mask really do?]]
* [[http://stackoverflow.com/questions/1462447/basics-of-php-opcode-cache|Basics of PHP opcode cache]]