Are you tired of slow PHP script execution and poor application performance? Do you struggle to optimize your code and reduce load times? If so, you’re not alone. Many developers face these challenges when working with PHP applications.
Fortunately, there’s a solution: OPcache.
This powerful opcode cache stores precompiled PHP script bytecode in shared memory, reducing the time it takes for your scripts to execute. Hence, it improves your PHP application performance, allowing you to focus on what really matters: delivering a great user experience.
In this blog post, I will guide you through the process of installing and configuring OPcache with your PHP app. More importantly, you will see how Cloudways has simplified the OPcache integration with PHP-based apps.
Brief Overview of OPcache
OPcache stores precompiled script bytecode in shared memory, improving PHP performance. It caches opcode, allowing scripts to be served directly from the cache. This reduces CPU and memory usage, optimizing resource utilization and enhancing PHP application scalability.
With OPcache enabled, scripts are stored in memory, and only updates are compiled. It eliminates the need for PHP to recompile scripts, reducing server overhead and speeding up PHP execution. This results in faster web page loading and a smoother user experience.
How Does OPcache Work?
PHP OPcache boosts performance by checking for precompiled script bytecode in shared memory each time a script is compiled. If the code is not found, OPcache automatically compiles it and saves it to memory, generating output afterward.
The diagram below illustrates the code execution process with PHP OPcache, clearly explaining how it works.
OPcache vs Other Caching
Different apps need different types of caching. PHP OPcache is great for speeding up PHP. This table compares different caching options.
Feature | PHP OPcache | APCu | Memcached |
Caching Mechanism | Opcode Cache | User Data Cache | Distributed Cache |
Integration | Bundled with PHP | Separate Extension | Separate Service |
Installation | Easy | Easy | Requires Server Setup |
Performance | Excellent | Good | Excellent |
Scalability | NA | NA | High |
Support for User Data | No | Yes | Yes |
Storage Mechanism | In-Memory | In-Memory | Distributed (RAM) |
Cache Expiration | NA | TTL or Manual Clear | TTL or Manual Clear |
Cache Invalidation | Automatic (File Change) | Manual Clear | Manual Clear |
Community Support | Strong | Strong | Strong |
Use Cases | Mainly used for opcode caching to speed up PHP execution | More suitable for caching user-specific data or distributed caching scenarios. | More suitable for caching user-specific data or distributed caching scenarios. |
Why Should You Use OPcache?
PHP OPcache is essential for any PHP-based web app, boosting performance and user experience. It stores precompiled bytecode in memory, eliminating repetitive parsing and compilation of PHP scripts.
This allows servers to handle more requests efficiently, making it easy to scale web apps without increasing server resources. OPcache also reduces disk I/O operations, speeding up PHP execution and improving website responsiveness.
With its compatibility with PHP, easy integration, and scalability, OPcache is a must-have for any PHP server environment, enhancing the performance and reliability of PHP-based web apps.
Performance of OPcache
I found a case study about how OPcache improved a website’s performance. A user named Tschallacka shared his server config and how requests were served quickly. The case study shows how OPcache can speed up and improve an application’s performance.
Without OPcache
When using this script without OPcache, 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
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 doesn’t need changing of functionality.
I choose explicitly for the framework files to 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.
System Requirements
To use OPcache, you need to compile it as a shared extension. If you’ve disabled default extensions, you must compile PHP with the –enable-opcache option. Then, you can load the OPcache extension into PHP using the zend_extension configuration directive.
With PHP 5.5 and later, you don’t need APC or similar bytecode caching extensions because OPcache is integrated into the core of PHP. This provides better stability and is officially supported by the PHP developers.
Unlock the Full Potential of PHP with OPcache Integration
Cloudways + OPcache: The Perfect Combination for a High-Performance Website.
Install and Configure OPcache
Although the latest update makes OPcache compatible with PHP 8. However, the experts recommend users opt for PHP v5 and v7. To start using OPcache, you must first enable it manually. 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, 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).
For PHP 5.4 or earlier (>= 5.2), you can install Zend OPcache using PECL. $ pecl install zendopcache-beta
The pecl command will try to update your configure php.ini automatically.
Now that you have set up OPcache properly, it’s time to update the recommended setting for performance optimization. The settings are as follows:
opcache.memory_consumption=128 (for caching all compiled files) opcache.interned_strings_buffer=8 opcache.max_accelerated_files=4000 (by default can cache 2000 files) opcache.revalidate_freq=60 opcache.fast_shutdown=1 opcache.enable_cli=1
Some other settings might be helpful like if you are using code annotations, you can use:
opcache.save_comments=1
You can see the full list of run-time configurations here.
OPcache With Other CMS/Framework
While PHP OPcache can improve performance, monitoring the caching behavior and adjusting settings based on your application’s needs is essential.
WordPress
- Compatibility Check: Before enabling PHP OPcache, ensure that your hosting environment and WordPress version are compatible with OPcache.
- Caching Plugin: Use a caching plugin specifically designed for WordPress, such as W3 Total Cache or WP Super Cache. These plugins can help you manage the caching settings, including PHP OPcache integration.
- Fine-tuning: Consider fine-tuning the PHP OPcache settings depending on the hosting environment. Adjust the opcache.memory_consumption, opcache.max_accelerated_files, and opcache.revalidate_freq based on your website’s requirements.
- Clear Cache Mechanism: Implement a cache-clearing mechanism to ensure that when you update plugins, themes, or content, the changes are reflected correctly. Some caching plugins handle this automatically.
Drupal
- Version Compatibility: Ensure you are using Drupal 7 or Drupal 8+, as earlier versions might not fully support PHP OPcache.
- Caching Modules: Drupal has modules like “APC” and “Memcache” that can be used in conjunction with PHP OPcache to enhance caching.
- OPcache Tuning: Adjust OPcache settings in the PHP configuration to optimize memory consumption and the number of cached files based on the size and complexity of your Drupal site.
- Cache Expiration: Implement a cache expiration mechanism to effectively handle content updates and changes.
Laravel
- OPcache Extension: Check that the OPcache extension is installed and enabled in your PHP setup for Laravel to utilize it.
- Optimization with Artisan: Laravel’s Artisan command-line tool provides an optimized command that pre-compiles classes, significantly reducing the time taken to load files.
- OPcache Settings: Fine-tune OPcache settings in your PHP configuration or use a package like “opcache-dashboard” to monitor and adjust settings from within Laravel
Using OPcache on Cloudways
Since Cloudways believes in providing ease to their customers, it allows you to change the memory settings from the server settings and packages tab.
While remember that you do not have access to the php.ini file, so the default values set up by Cloudways will be applied. You can change both options’ memory sizes according to your app requirements.
The default setup values are as follows:
opcache.interned_strings_buffer=4 opcache.max_accelerated_files=2000 opcache.memory_consumption=64 opcache.revalidate_freq=2 opcache.fast_shutdown=0 opcache.enable_cli=0
OPcache Graphical GUI
The traditional way to check if PHP OPcode caching is running on the server is to write phpinfo(); in the .php file and see the status:
But if you want to see the optimized Graphical GUI with user interaction in which you can have the option to manage settings with buttons, then you can use the open-source packages available on GitHub. So the following packages can be used for the job.
1. OPcacheGUI
OPcacheGUI allows you to manage OPcache features like status, configs, reset, scripts overview, etc, with a nice UI. You can also see the memory, keys, and hits status in graphical form. Thus simplifying the overall data process for users.
– Source: GitHub/PeeHaa
2. OPcache-Status
OPcache-Status provides the one-page status page for PHP OPcode caching. A few more things it can do for you are:
- The ability to sort the list of cached scripts by the various columns;
- A better layout that can accommodate more of the script data without looking cluttered;
- A tuning suggestion tab (needs to add a couple of things to the OPcache output first though).
– Source: GitHub/rlerdorf
3. OPcache-GUI
OPcache-GUI gives you an easy-to-use UI for OPcache settings, built with jQuery and React. You can see info like your host, platform, version, and when it was last reset. It also shows all the available functions and important stats like the number of hits and memory usage.
– Source: GitHub/amnuts
Summary
By now, you’re probably convinced of the benefits of integrating PHP OPcache into your web applications. This powerful tool has revolutionized PHP performance, providing a major boost to the speed and efficiency of your web apps.
With code caching, you no longer have to waste time compiling code repeatedly. Instead, code is only compiled when it’s updated and then saved into shared memory for lightning-fast access. This saves time and resources, resulting in a seamless performance.
Don’t miss out on the opportunity to take your PHP performance to the next level with OPcache!
Q. How do I enable PHP opcode caching?
A. To enable PHP opcode caching, here is the below-given code you will need to change in your php.ini file.
config: 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
Q. How do I disable PHP opcode caching?
A. To disable PHP’s opcode caching, open your SSH terminal and go to the root, then edit the below-given file:
/etc/php7.2-sp/conf.d/opcache.ini
opcache.enable=0
sudo service php7.2-fpm-sp restart
Q. How to clear PHP OPcache?
A. To clear PHP OPcache content, Reload the PHP module/daemon used by the web server, and the OPcache contents will be deleted. Run the following given commands to complete the process:
# when using mod_php and Apache $ apachectl graceful # when using PHP-FPM $ service php-fpm reload
Q. What to do if PHP Opcache is not working?
A. If the PHP Opcache doesn’t work properly, go to the php.ini file and check the Opcache section. Make sure that the opcache.enable=1 is set in this file. If not, then set it accordingly.
Shahzeb Ahmed
Shahzeb is a Digital Marketer with a Software Engineering background, works as a Community Manager — PHP Community at Cloudways. He is growth ambitious and aims to learn & share information about PHP & Laravel Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]