Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How exactly is a PHP script executed?

I was just thinking to myself "How exactly is a PHP script executed?" I thought it was parsed first for syntax errors etc, and then interpreted and executed.

However, I don't know why I believe that is correct. I'm probably wrong.

So, how exactly is a PHP file interpreted and executed? What stages does this involve? How do included files fit into the parsing of the script?

This is just to help me get my head around it. I'm interested and can not find a good answer with Google.

like image 769
alex Avatar asked Apr 27 '10 10:04

alex


People also ask

Where does PHP scripts are executed?

PHP code is executed on the server.

How is PHP executed in browser?

Navigate to "localhost:8888" in your browser's address bar. The address bar is where you normally see "https://www." To do this, type "localhost:8888" and press ↵ Enter (Windows) or ⏎ Return (Mac). You'll see a directory of your PHP files displayed on the page. Click the PHP file to run the script in your browser.


2 Answers

PHP is a compiled language since PHP 4.0

The idea of what is a compiler seems to be a subject that causes great confusion. Some people assume that a compiler is a program that converts source code in one language into an executable program. The definition of what is a compiler is actually broader than that.

A compiler is a program that transforms source code into another representation of the code. The target representation is often machine code, but it may as well be source code in another language or even in the same language.

PHP became a compiled language in the year 2000, when PHP 4 was released for the first time. Until version 3, PHP source code was parsed and executed right away by the PHP interpreter.

PHP 4 introduced the the Zend engine. This engine splits the processing of PHP code into several phases. The first phase parses PHP source code and generates a binary representation of the PHP code known as Zend opcodes. Opcodes are sets of instructions similar to Java bytecodes. These opcodes are stored in memory. The second phase of Zend engine processing consists in executing the generated opcodes.

Form more information go to http://www.phpclasses.org/blog/post/117-PHP-compiler-performance.html

like image 190
Vishnu Saini Avatar answered Sep 20 '22 23:09

Vishnu Saini


Basically, each time a PHP script is loaded, it goes by two steps :

  • The PHP source code is parsed, and converted to what's called opcodes
    • Kind of an equivalent of JAVA's bytecode
    • If you want to see what those look like, you can use the VLD extension
  • Then, those opcode are executed

These slides from Sebastian Bergmann, on slideshare, might help you understand that process a bit better : PHP Compiler Internals

like image 43
Pascal MARTIN Avatar answered Sep 22 '22 23:09

Pascal MARTIN