OPcache is a form of caching system that caches precompiled script bytecode in a server's memory, allowing a web page to load faster each time a user accesses it. With the OPcache PHP OPcode caching system, you can speed up your website three times.
In this article, we will discuss what is OPcache and how to use it to speed up your website.
Here is how it’s done:
- What is Caching?
- What is OPcache?
- Why OPcache?
- How does OPcache Work?
- How can We Tell If OPCache is Caching Files?
- How to Use PHP OPCache?
- OPcache vs. APC Caches
- Installing OPcache on Your Server
What is Caching?
Caching is a system that you can use to make your website load faster. It works by saving content to the memory of your server the first time it is loaded on a web page. The saved content is recovered from memory and served on subsequent page loads.
Because of this, cached content loads much faster than content loaded directly from the server.
It's the equivalent of learning your multiplication tables by heart. It's far faster to recite the answer to a multiplication problem from memory once you've memorized it than trying to calculate the answer all over again once you've memorized it.
A cache operates similarly. Content is saved in a server's memory so that it can be loaded fast rather than having to go all the way to the server, which takes longer.
Your website will load more quickly as a consequence.
What is OPcache?
OPcache is an opcode cache that uses shared memory to store precompiled PHP script bytecode for speedier execution. OPcache will speed up PHP-based services, saving you time when building your script.
OPcache is included in PHP 5.5 and is also available in newer versions. To manually enable OPcache in earlier versions of PHP, such as PHP 5.4, 5.3, and 5.2, you must first install the pecl extension.
According to the website php.net:
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.
After you finish a PHP code compilation, the human-readable code is translated to machine language, and compiling all of the scripts takes time. As a result, if you make a request every time and the cycle continues, your application will experience a lot of performance issues.
However, if PHP OPcache is enabled, the process will only execute once, caching all scripts and compilation times. Only the updates will compile and continue to save the scripts, which will be stored in memory.
This can provide you with a huge performance boost and significantly cut the time it takes for your application to load. PHP7 OPcache, on the other hand, uses 64MB of memory by default.
OpCache is a PHP extension that greatly enhances the performance of PHP-based websites when deployed. The OpCache is ready to use right away (by default, after installation). By lowering the time, it takes to compile code, OPcache can help you improve speed.
The first time PHP code is compiled, it is saved in the server's memory. Instead of waiting for the code to compile, the pre-compiled version is utilized each time the code is called, causing a delay each time the code is invoked and improving the Website's performance.
Consider the following scenario: you have a small website with average daily traffic of 500-5k visitors. The number of concurrent users is also limited, ranging from 5 to 10 each day. There will be no big performance concerns in this instance, and the users will be perfectly entertained.
Imagine a website or application that receives hundreds of thousands of visitors per second and has a concurrent user ratio of thousands. PHP7 OPcache can provide you with ideal performance relief because it only a few configuration steps to witness the significant speed and performance benefits.
Another thing to keep in mind is that OPcache alone will not be able to handle everything; your server's settings and configuration will also play a role. In this scenario, though, your coding structure is also crucial.
While OPcache is disabled, a Digitalocean 1GB RAM server with 1 CPU can handle 10 requests per second. By allowing it, the number of requests per second will increase to 34 or more. You can also improve it further to improve the application's performance.
How does OPcache Work?
Whenever a PHP script is requested, it is parsed and compiled into opcode, which is then executed by the Zend Engine. This is what allows PHP developers to avoid the compilation stage that other languages, such as Java or C#, require – you can make changes to your PHP code and see the results right away.
The parsing and compiling stages, on the other hand, slow down your response time and are generally unneeded in a non-development environment because your application code changes infrequently.
Following the interpretation and conversion of a PHP script into an opcode, the opcode is saved in shared memory, and subsequent requests will skip the parsing and compilation steps and use the opcode stored in memory, decreasing PHP execution time.
The flowchart below will help you understand how OpCache works on a PHP website.
How can We Tell If OPCache is Caching Files?
If you've already installed and configured OpCache, you may want to keep track of which PHP files are cached. The entire caching engine runs in the background, invisible to visitors and website developers.
You can use one of the two functions that offer this information to check its status:
Fortunately, there are a handful of scripts that will download all of the OpCache configuration and status data and show it in a friendly manner. You don't need to write any code; simply choose one of the tools listed below:
- Opcache Control Panel
- opcache-status by Rasmus Lerdorf
- opcache-gui by Andrew Collington
- OpCacheGUI by Pieter Hordijk
In some projects, we use the opcache-gui script, which includes all of the features we require. Simply look at the percentages in the "Overview" tab of the opcache-gui website to see if the caching engine is working properly.
If the memory use and hit rate metrics are greater than zero, the OpCache is caching the PHP code and handling the requests using the cached files. Navigate to the tab "File use" to get a list of specific PHP files that are cached. Check the file list to see if the files in your projects have been cached.
How to Use PHP OPCache?
The OPCache is used to improve PHP efficiency by storing precompiled bytecode and therefore eliminating the need to load and parse PHP scripts on each request.
For the intended use, packages like Zend OPCache are required. PHP versions 5.2, 5.3, and 5.4 are included in the zendOPCache package. This module is used to meet the basic need of opcode caching and hence optimization.
It will boost PHP efficiency by storing precompiled bytecode in shared memory, removing the need to retrieve code from disk and compile it for future use.
For the ZendOPCache package download (direct download links):
Functions of OPCache:
1. opcache_compile_file() Function
This function builds a PHP script and caches it without running it.
bool opcache_compile_file( $file )
This function compiles a PHP script and adds it to the opcode cache without running it; it can be used to prime the cache following a web server restart by pre-caching files that will be utilized in subsequent requests.
As an argument, $file is used. It's the location of the PHP script that needs to be compiled. If the file was successfully compiled, the above description returns true; otherwise, it returns false.
2. opcache_get_configuration() Function
This function is used to retrieve cache configuration information.
array opcache_get_configuration( void )
This function returns cache instance configuration data as well as an array of information that includes the ini file.
3. opcache_get_status() Function
This function is used to obtain information about the cache's status.
array opcache_get_status( $get_scripts = TRUE )
This function returns the cache instance's state information, with the parameter $get_scripts containing script-specific state information.
4. opcache_invalidate() Function
This function is used to invalidate a script that has been cached.
bool opcache_invalidate( $script, $force = FALSE )
This function clears the opcode cache of the specified script. If force is unset or FALSE, the script will be invalidated only if the script's modification time is newer than the cached opcodes.
The option $script denotes the path of the script that is being invalidated. If the argument $force is set to TRUE, the script will be invalidated regardless of whether invalidation is required.
5. opcache_is_script_cached() Function
It will inform you whether or not a script has been cached in OPCache.
bool opcache_is_script_cached( $file )
This function determines whether or not a PHP script has been cached using OPCache. This might be used to more readily discover the cache's "warning" for a specific script. The $file option specifies the location of the PHP script to be checked.
6. opcache_reset() Function
The contents of the opcode cache are reset using this function.
bool opcache_reset( void )
This function clears the opcode cache completely. All scripts will be reloaded and reparsed the next time they are hit after executing opcache_reset().
OPcache vs. APC Caches
Opcode caching systems include OPcache, APC, and Xcache. Alternative PHP Cache (APC) was a free, open-source extension for PHP that was once owned by Zend. Another solution was to use Xcache.
APC was extensively used, but it lacked the support that OPcache did, making it difficult to maintain and stable with each new PHP release.
Since PHP version 5.5, Zend has made OPcache open source and available as an extension. Earlier versions gave you the option of using APC or OPcache; but, if you want to use the latter, you must manually install it.
Xcache, on the other hand, is a solid PHP accelerator alternative to OPcache.
Do we need both APC and OPcache?
The answer is no. Having APC installed is optional if you have PHP OPcache enabled on your servers. APC is a caching system that was included in prior versions of PHP, but it does not operate with PHP 5.5 or newer versions such as PHP 7.x. You must transition from APC to OPcache, and if you try to utilize it forcibly, you may get issues.
With PHP 5.5 and beyond, APC (or any other bytecode caching extension like XCache) is no longer required. OPcache is directly integrated into the heart of the software by the PHP developers. This not only improves overall product stability but is also formally endorsed by PHP developers, implying a large working community.
Installing OPcache on Your Server
OPcache PHP opcode caching is installed and activated by default if you have PHP version 5.5 or higher. There's nothing else you need to do. It also doesn't require any additional setups or requirements to run.
That's also why, if you look for alternatives, you won't discover any.
According to the PHP manual:
OPcache can only be compiled as a shared extension. If you have disabled the building of default extensions with --disable-all, you must compile PHP with the --enable-opcache option for OPcache to be available.
Once compiled, you can use the zend_extension configuration directive to load the OPcache extension into PHP. This can be done with zend_extension=/full/path/to/opcache.so on non-Windows platforms, and zend_extension=C:\path\to\php_opcache.dll on Windows.
To restart PHP on Apache, run the command below.
Enter the following for Nginx:
service nginx restart
Installing OPcache on Older Versions
If your server is running PHP versions 5.2, 5.3, or 5.4, run the PECL command following to manually install OPcache:
pecl install zendopcache-beta
After that, go to your php.ini file and make the following changes:
pecl config-get php_ini
You'll need to change the following recommended values in your php.ini file:
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
Your php.ini file is usually located in the file folder system of your system. Contact your hosting provider if you're not sure where to look.
In summary, opcode caches are a quick solution to reduce PHP application latency and should always be enabled in production PHP environments. The decrease in response time will be primarily determined by two factors:
- The amount of time spent in PHP by the request. If your application spends a lot of time waiting for a database to deliver results or relies on slow third-party web services, an opcode cache will result in a slower response time.
- When compared to using a framework, the reduction in response time will be restricted if your PHP scripts are very basic, including only the bare minimum of code to handle the request. Upgrade to PHP 5.5 or install Zend OpCache now to get started.
Atatus: PHP Performance Monitoring and Log Management
Atatus is an Application Performance Management (APM) solution that collects all requests to your PHP applications without requiring you to change your source code. However, the tool does more than just keep track of your application's performance. It monitors logs from all of your PHP applications and systems into a centralized and easy-to-navigate user interface, allowing you to troubleshoot faster.
We give a cost-effective, scalable method to centralized PHP logging, so you can obtain total insight across your complex architecture. To cut through the noise and focus on the key events that matter, you can search the logs by hostname, service, source, messages, and more. When you can correlate log events with APM slow traces and errors, troubleshooting becomes easy.