Yunus Emre Vurgun's Blog

How Does PHP Run?

Have you ever wondered how your PHP source code gets to run? At some point, you installed PHP and started writing your scripts. You connected to your XAMPP MySQL with a few lines of code and it's magic! Well, maybe it is not magic after all.

PHP is an interpreted (interpreter produces a result from your code but compiler turns your program into assembly) scripting language for server-side programming. It first appeared in 1995, 27 years ago.
So how does it run? It needs an interpreter to run, and that is the "Zend Engine". This engine has several duties that allow us to run our PHP programs. It compiles your source code into bytecode, then it goes into its virtual machine that executes this new bytecode, and you have yourself a running PHP program.
As of PHP 8, you can compile your code via the JIT Compiler. What is the difference?
 Well, JIT is a "just in time" compiler, and this means that now you can "compile" your program into machine code directly.
So, before PHP 8 and JIT, how did the Zend Engine work?
 We first need to talk about caching. A cache is a collection of duplicate data. This is something we need to have because accessing the necessary data directly will take longer.
 PHP uses caching to reduce the time of page generation. You wouldn't want your WordPress website's visitors to wait too long, would you? That's why.
PHP has a caching engine to do the caching. This engine is called the "OPCache," and it is built into PHP.
 OPCache stores the precompiled bytecode in the shared memory, and because of this, the need to load the actual script on every request from the visitor/client is not needed.
Here is the visual diagram of the process of running PHP, including OPCache and JIT, but of course, this is an extremely simplified version of how things work:

We need to keep in mind that things get more detailed and complicated as you dig into them. In this brief explanation, I tried to explain the big picture as a whole, but there are endless details in PHP that will enlighten us step by step as we learn more.

Sources:

https://www.php.net/manual/en/intro.opcache.php

https://www.php.net/manual/en/intro.wincache.php

https://www.droptica.com/blog/how-php-interpreter-works/

https://en.wikipedia.org/wiki/PHP

https://help.dreamhost.com/hc/en-us/articles/216660668-OPcache-overview#:~:text=OPcache%20is%20a%20caching%20engine,parse%20scripts%20on%20each%20request.

https://www.droptica.com/blog/jit-compiler-php-8/

https://en.wikibooks.org/wiki/PHP_Programming/Caching#:~:text=A%20cache%20is%20a%20collection,to%20minimize%20page%20generation%20time.

June 9, 2023