254

PHP 5.5 has been released and it features a new code caching module called OPCache, but there doesn't appear to be any documentation for it.

So where is the documentation for it and how do I use OPcache?

Danack
  • 24,939
  • 16
  • 90
  • 122
  • 3
    https://blogs.oracle.com/opal/entry/using_php_5_5_s – Funk Forty Niner Jun 20 '13 at 22:17
  • 4
    Documentation: http://www.php.net/manual/en/book.opcache.php – David Oliver Apr 09 '14 at 11:44
  • Too bad that the Documentation does NOT tell us how to compile *opcache* correctly / disable it nor workaround the autoconf of PHP 5.6.24+ source, so that PHP would compile! :-( – Filip OvertoneSinger Rydlo Sep 20 '16 at 11:58
  • 1
    @Fred-ii- *"There are a lot of settings which may need adjusting. Understanding how it works and identifying issues during the stabilization phase of PHP 5.5 release process will greatly help."*... That blog post isn't very helpful. It doesn't explain how to understand how it works or how best to adjust the settings :( – icc97 Mar 16 '17 at 22:09

5 Answers5

378

Installation

OpCache is compiled by default on PHP5.5+. However it is disabled by default. In order to start using OpCache in PHP5.5+ you will first have to enable it. To do this you would have to do the following.

Add the following line to your php.ini:

zend_extension=/full/path/to/opcache.so (nix)
zend_extension=C:\path\to\php_opcache.dll (win)

Note that when the path contains spaces you should wrap it in quotes:

zend_extension="C:\Program Files\PHP5.5\ext\php_opcache.dll"

Also note that you will have to use the zend_extension directive instead of the "normal" extension directive because it affects the actual Zend engine (i.e. the thing that runs PHP).

Usage

Currently there are four functions which you can use:

opcache_get_configuration():

Returns an array containing the currently used configuration OpCache uses. This includes all ini settings as well as version information and blacklisted files.

var_dump(opcache_get_configuration());

opcache_get_status():

This will return an array with information about the current status of the cache. This information will include things like: the state the cache is in (enabled, restarting, full etc), the memory usage, hits, misses and some more useful information. It will also contain the cached scripts.

var_dump(opcache_get_status());

opcache_reset():

Resets the entire cache. Meaning all possible cached scripts will be parsed again on the next visit.

opcache_reset();

opcache_invalidate():

Invalidates a specific cached script. Meaning the script will be parsed again on the next visit.

opcache_invalidate('/path/to/script/to/invalidate.php', true);

Maintenance and reports

There are some GUI's created to help maintain OpCache and generate useful reports. These tools leverage the above functions.

OpCacheGUI

Disclaimer I am the author of this project

Features:

  • OpCache status
  • OpCache configuration
  • OpCache statistics
  • OpCache reset
  • Cached scripts overview
  • Cached scripts invalidation
  • Multilingual
  • Mobile device support
  • Shiny graphs

Screenshots:

status

cached-scripts

graphs

mobilr

URL: https://github.com/PeeHaa/OpCacheGUI

opcache-status

Features:

  • OpCache status
  • OpCache configuration
  • OpCache statistics
  • Cached scripts overview
  • Single file

Screenshot:

status

URL: https://github.com/rlerdorf/opcache-status

opcache-gui

Features:

  • OpCache status
  • OpCache configuration
  • OpCache statistics
  • OpCache reset
  • Cached scripts overview
  • Cached scripts invalidation
  • Automatic refresh

Screenshot:

opcache-gui-overview

URL: https://github.com/amnuts/opcache-gui

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
  • 6
    Anything in regard of PHP-CLI? How CLI utilizes it? When FPM restarted, OPCache resets - does it also affect CLI's OPCache? Is CLI's OPCache separate or does it share same Cache pool with FPM? Thanks! – Gelmir Feb 25 '14 at 13:00
  • 3
    OpCache was enabled by default for me on my most recent installation on ubuntu 14.04, apache 2.4.7, php 5.5.9. – jstats May 20 '14 at 02:41
  • hi, in your 3rd screenshot, cache_full is false, i am assuming its related to full page caching, could you please tell me how to turn it on? (make it true) – brucekaushik Sep 25 '14 at 14:58
  • I am wrong, that is not for caching full page, but it will show up as true if the memory that the cache uses is full. Thanks anyways! – brucekaushik Sep 25 '14 at 15:29
  • zend_extension=C:\path\to\php_opcache.dll (win) - Adding this line in php.ini works fine. – Kalidasan Nov 25 '15 at 05:35
  • apaxhe can't find `zend_extension=C:\path\to\php_opcache.dll` buth the file is there, what's wrong? – davejal Jun 06 '17 at 14:44
  • 2
    Note that if you are using `Xdebug` extension, it MUST be loaded AFTER the `OpCache` extension. – Yousha Aleayoub Sep 17 '17 at 22:50
153

OPcache replaces APC

Because OPcache is designed to replace the APC module, it is not possible to run them in parallel in PHP. This is fine for caching PHP opcode as neither affects how you write code.

However it means that if you are currently using APC to store other data (through the apc_store() function) you will not be able to do that if you decide to use OPCache.

You will need to use another library such as either APCu or Yac which both store data in shared PHP memory, or switch to use something like memcached, which stores data in memory in a separate process to PHP.

Also, OPcache has no equivalent of the upload progress meter present in APC. Instead you should use the Session Upload Progress.

Settings for OPcache

The documentation for OPcache can be found here with all of the configuration options listed here. The recommended settings are:

; Sets how much memory to use
opcache.memory_consumption=128

;Sets how much memory should be used by OPcache for storing internal strings 
;(e.g. classnames and the files they are contained in)
opcache.interned_strings_buffer=8

; The maximum number of files OPcache will cache
opcache.max_accelerated_files=4000

;How often (in seconds) to check file timestamps for changes to the shared
;memory storage allocation.
opcache.revalidate_freq=60

;If enabled, a fast shutdown sequence is used for the accelerated code
;The fast shutdown sequence doesn't free each allocated block, but lets
;the Zend Engine Memory Manager do the work.
opcache.fast_shutdown=1

;Enables the OPcache for the CLI version of PHP.
opcache.enable_cli=1

If you use any library or code that uses code annotations you must enable save comments:

opcache.save_comments=1

If disabled, all PHPDoc comments are dropped from the code to reduce the size of the optimized code. Disabling "Doc Comments" may break some existing applications and frameworks (e.g. Doctrine, ZF2, PHPUnit)

kittycat
  • 14,983
  • 9
  • 55
  • 80
Danack
  • 24,939
  • 16
  • 90
  • 122
  • Found that link too, but I knew you'd dig a bit more ;-) – Funk Forty Niner Jun 20 '13 at 22:18
  • I'm going for the tag badge :) – Danack Jun 20 '13 at 22:21
  • There's a tag "badge"? ;-) – Funk Forty Niner Jun 20 '13 at 22:22
  • 4
    Are those recommended settings for production environments, for development, or both? – marcvangend Aug 26 '13 at 09:15
  • 1
    Maybe a misunderstanding on my part of what exactly opcache is and what it is used for but I have it configured and tested with PeeHaa status script below. All is working. But I'm still asking the OP question. "How to use it?" It's not for caching views and things is it? – isimmons Oct 10 '13 at 15:10
  • 3
    @isimmons "OPcache improves PHP performance by storing precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request." – Danack Oct 10 '13 at 15:20
  • Yep, just figured that out. Thought it's worth the comment because google led me here before I figured it out. – isimmons Oct 10 '13 at 15:22
  • 1
    @marcvangend Good point ! I think caching makes only real sense in production, so these configs are probably production settings. – Sliq Nov 11 '13 at 11:01
  • 3
    Can anyone explain why recommended settings performance is worse than default or when they should start giving effect? – R.P Dec 04 '14 at 18:00
  • `opcache.save_comments=1` has also to be set for Symfony2. – COil Jul 07 '15 at 10:39
  • 1
    There is [an issue](https://bugs.php.net/bug.php?id=69190) where fast_shutdown causes segmentation faults (and therefore 500 errors) which means you may wish to set it to 0 until it is fixed. – GreenReaper Aug 02 '15 at 13:42
  • 1
    Warning : don't enable OPcache if you use PHP in a chroot jail (shared hosting, for example) because of **security issue #69090** : https://bugs.php.net/bug.php?id=69090 – Levure Sep 06 '15 at 16:52
  • 1
    Keep `opcache.fast_shutdown=0` untill this bug is fixed: http://github.com/zendtech/ZendOptimizerPlus/issues/146 – Yousha Aleayoub Sep 17 '17 at 22:52
21

I am going to drop in my two cents for what I use opcache.

I have made an extensive framework with a lot of fields and validation methods and enums to be able to talk to my database.

Without opcache

When using this script without opcache and I push 9000 requests in 2.8 seconds to the apache server it maxes out at 90-100% cpu for 70-80 seconds until it catches up with all the requests.

Total time taken: 76085 milliseconds(76 seconds)

With opcache enabled

With opcache enabled it runs at 25-30% cpu time for about 25 seconds and never passes 25% cpu use.

Total time taken: 26490 milliseconds(26 seconds)

I have made an opcache blacklist file to disable the caching of everything except the framework which is all static and doesnt need changing of functionality. I choose explicitly for just the framework files so that I could develop without worrying about reloading/validating the cache files. Having everything cached saves a second on the total of the requests 25546 milliseconds

This significantly expands the amount of data/requests I can handle per second without the server even breaking a sweat.

Tschallacka
  • 27,901
  • 14
  • 88
  • 133
  • With "opcache enabled" means what configuration did you use to set it up?Only enabling it in the ini file or any other configuration is needed? – KillABug Feb 20 '15 at 10:02
  • 3
    `zend_extension=php_opcache.dll; opcache.memory_consumption=128; opcache.interned_strings_buffer=8; opcache.max_accelerated_files=4000; opcache.revalidate_freq=60; opcache.fast_shutdown=1; opcache.enable_cli=1; opcache.blacklist_filename="C:\xampp\php\cfg\opcache.blacklist;` Just replace the ; with an enter in the ini file. But this is what I used. mostly default stuff – Tschallacka Feb 20 '15 at 10:28
  • 1
    btw, me running this with memcache doing 2100 database requests a second runs the script I use within 150 microseconds(about 1/6th of a millisecond) – Tschallacka Feb 20 '15 at 10:31
  • that will help me in going ahead though I dont use memcache right now,I believe opcache can help on the PHP front.Correct me if I am wrong. – KillABug Feb 23 '15 at 12:21
  • 1
    Opcache caches the php files in compiled form in memory. So you don't have overhead of reading from disk and compiling & optimizing of files by the php parser anymore. Memcache is something you can use to store variables in between sessions. Sayt for example a user has an update script that requests the same parameters for 10 seconds whilst user stares at ascreen. You could use mem cache to compile the query once, and then keep requesting the compiled query from memory isntead of regenerating it. – Tschallacka Feb 23 '15 at 12:25
  • Thank you for the above info!And does opcache check each time if the php files are updated?I mean how does it come to know about the files are updated and need to be recompiled? – KillABug Feb 23 '15 at 12:30
  • 2
    it doesn't. `opcache.revalidate_freq=60;` determines how long a file may live in memory in seconds. when the time is up it recompiles the file. – Tschallacka Feb 23 '15 at 12:51
  • Great info!!I will add comments in case I get stuck at any point! :P – KillABug Feb 23 '15 at 13:33
  • 3
    Actually, `opcache.revalidate_freq` controls how often a script is checked for changes (based on whether its timestamp changed). So if a script's timestamp remains the same as the last time it was compiled, it won't be recompiled. All of this is assuming you haven't changed the `opcache.validate_timestamps` setting, which is enabled by default. – jjlin Aug 12 '15 at 18:12
  • Ah, thanks for clarifying that. I assumed there would be a rudementary check like that – Tschallacka Aug 12 '15 at 18:14
  • @jjlin - When you say it won't be recompiled, do you mean it remains in memory indefinitely or until PHP or the web server is restarted? Second, if `opcache.validate_timestamps` is enabled by default i.e.`opcache.validate_timestamps=1`, do you mean that `opcache.revalidate_freq` only validates if the timestamp has changed every 60 seconds? – Motivated Dec 05 '20 at 01:05
4

With PHP 5.6 on Amazon Linux (should be the same on RedHat or CentOS):

yum install php56-opcache

and then restart apache.

Roger Dueck
  • 615
  • 7
  • 16
3

I encountered this when setting up moodle. I added the following lines in the php.ini file.

zend_extension=C:\xampp\php\ext\php_opcache.dll

[opcache]
opcache.enable = 1
opcache.memory_consumption = 128
opcache.max_accelerated_files = 4000
opcache.revalidate_freq = 60

; Required for Moodle
opcache.use_cwd = 1
opcache.validate_timestamps = 1
opcache.save_comments = 1
opcache.enable_file_override = 0

; If something does not work in Moodle
;opcache.revalidate_path = 1 ; May fix problems with include paths
;opcache.mmap_base = 0x20000000 ; (Windows only) fix OPcache crashes with event id 487

; Experimental for Moodle 2.6 and later
;opcache.fast_shutdown = 1
;opcache.enable_cli = 1 ; Speeds up CLI cron
;opcache.load_comments = 0 ; May lower memory use, might not be compatible with add-ons and other apps

extension=C:\xampp\php\ext\php_intl.dll

[intl]
intl.default_locale = en_utf8
intl.error_level = E_WARNING

intl -> http://php.net/manual/en/book.intl.php

Anoop Toffy
  • 918
  • 1
  • 9
  • 22