Configure PHP OpCache to Improve Speed

Improve the speed of your website

In the last article, we overviewed the working of PHP OpCache and how the request bypasses the intermediate interpreter step when opcache is enabled. Now, let's configure the opcache in the PHP configuration file. For my system, the file is located at /etc/php/7.3/fpm/php.ini. Generally, you'll find the file located at /etc/php/{version}/... in Ubuntu or Linux based operating system.

 

Firstly, change the opcache.enable flag to 1. This will enable the caching of opcode for your server. 0 means disabled.


opcache.enable=1

 

Next, you can configure the memory consumed by the opcache. By default it is 128MB but if you have server with higher memory you can optimise it accordingly. Before setting the memory, consider other services which might consume server's memory like MySQL, Elastic, RabbitMQ, etc. You can explore opcachegetstatus() to get an approximate value.


opcache.memory_consumption=128

 

We can set the maximum number of files which will be cached by opcache in the memory. You can do a quick find . -type f -print | grep php | wc -l to get the count of the files used by your codebase. Keep the value greater than your file count.


opcache.max_accelerated_files=10000

 

After how many seconds does the opcache needs to check for new code? We can set this using the following line. 0 means always check which is equivalant to not setting the opcache. In your development environment set this to 0, for production the value of opcache.validate_timestamps plays an important role.


opcache.revalidate_freq=3600

 

If we set opcache.validate_timestamps=0, opcache will never validate the files against the changes with the source code and you will have to restart your PHP service every time you deploy your code (i.e. change the source). If it is set to 1, the files are check based on the opcache.revalidate_freq. So, here, each file will be checked after 3600 seconds.


opcache.validate_timestamps=0

 

Coming to restarting the PHP service, if the opcache is enabled we can use opcache.fast_shutdown=1, which provides a faster way to call the deconstructors in the code at the end of a single request and thus speed up the response and recycle PHP workers so they're ready for the next incoming request faster.


opcache.fast_shutdown=1

 

Another intresting configuration is opcache.interned_strings_buffer. This makes sure that any hardcoded string values will be cached once and will be shared among all php-fpm processes. For example, you have a string "Codegear", and you loop it 100 times. Opcache will cache it once and point other usages to this memory location. Not only this, it will also use this cached value in all the php-fpm processes thus saving lot of memory space. The default value is 8 which is 8MB.


opcache.interned_strings_buffer=16