Menu
Is free
registration
home  /  Advice/ Free PHP compilers. A selection of online compilers: we run and test the code right in the browser How the interpreter works

Free PHP compilers. A selection of online compilers: we run and test the code right in the browser How the interpreter works

Compiling PHP from source is more often done on Unix-like systems. Those on a Windows operating system will most likely download and install PHP from binary packages. And while I disagree that it's easier to use, the precompiled solution is even on Unix systems there are some benefits that can come with compiling binary from source. All in all:

  • You have a chance fine tuning the final product when compiled. Maybe you want definite extension which compiles directly to binary rather than loading it as an external library. Or perhaps you want to turn off what is usually available by default.
  • You can do a trick, at compile time, if needed, which can improve performance for a particular environment (of course, this assumes that you already know what you are doing in this case. you would not read this article !).
  • Compiling may be the only way to get things to work if the compiled binaries were built on older versions with software and library support and you are now on a new system.

A warning: compilation can be frustrating, especially on Windows! You must ensure that the build environment is set up correctly, learn how to use the compiler and other build tools as expected, and satisfy any dependency libraries. We hope this article is your first step in overcoming many of these obstacles.

Setting up the build environment

PHP is written in C and therefore a C compiler is necessary if you are going to build PHP from source. C ++ is a super suite of C, so a good C ++ compiler should be able to compile C code, and although this is not always the case. For Windows, Visual Microsoft, C + + Express (which will later be called VC + +) freely available on the Microsoft website. The 2010 edition was used.

When choosing a compiler version, you should keep in mind how you will be running PHP. If you have to work with mod_php from the officially compiled Apache binaries and want to compile PHP using Visual Studio 6, since this is the Apache compile version. The module should target the same runtime library as Apache, in this case msvcrt.dll. If you are building Apache from source as well, or if you intend to run PHP as FastCGI or CLI then this is not a problem and 2010 will work fine.

You must also install software Windows Development Kit (SDK after). The SDK gives us important header files for Windows platforms which we need to compile successfully. This too, version 7.1 was used.

Install the compiler and then the SDK. I will not discuss the installation, as both have a graphical installation wizard that guides you through the entire process.

Once you have a working compiler to build, download Binary Tools and Known Packages from windows.php.net. The binary tools package (I am using the 20110915 archive) contains development tools like re2c, bison, and some additional commands that you will need to build PHP. A well-known package (I am using the 5.4 archive because this is the same as the PHP version I will be compiling) contains the minimum headers and library dependencies needed, eg zlib.h.

It probably goes without saying that you want to download the PHP source as well from windows.php.net. At the time of this writing, the current version is PHP 5.4.6, so you will see this version number in the examples.

It's a good idea to create working space, to which you can unpack the source code and compile so that they do not affect the rest of your system. Create a C: \ PHP-Dev folder to serve as your working directory and then unpack the binary archive and tools into it.

Next, unpack the contents of the archive, PHP source in C: \ PHP-Dev now you have php5.4 in your source folder, and then extract its deps archive into the deps sibling folder. The directory structure should look something like this:

Open the Windows SDK Command Prompt that was installed with the SDK (Start => Microsoft Windows SDK => Windows SDK Command Prompt) and execute the following commands:

Setenv / release / xp / x86 cd C: \ PHP-Dev bin \ phpsdk_setvars.bat

Using the command line SDK console preferably before the regular cmd.exe console as it sets a lot environment variables compilation-specific source code... Command compilations later must also be done in this console.

setenv set some build properties for the environment, in this case the target Windows XP 32-bit build environment is set. You can try and build with / x64 if you're looking for adventure. Definition of various Windows versions such as / Vista, most likely exit problems due to some strange definitions in scripts (PHP still wants to be XP compatible). Unless you really know what you are doing, it is probably safest to stick to the recommended values ​​I used above.

phpsdk_setvars.bat script goes out to some additional environment variables, the build process was able to find binary tools.

Keep in mind that all of these setting variables are just temporary console sessions. If you close everything quickly to return to compilation later, you will need to run the command again, and if you do not, you will receive errors like the following, when you later run the configuration, you will not be able to continue:

Checking for bison.exe ... ERROR: bison is required

Making sure you have the correct build environment, required sources, and no dependencies is the hardest part of the process. So now your environment is set up from source and dependencies in place, it's time to compile!

Compiling PHP

From the SDK command line, go to the PHP source folder and run buildconf. The command is responsible for generating configuration files, which will be generated by the Makefile to control the compilation process.

After buildconf finishes (it only takes a second), run configure --help - and see the help for what features you want to enable / disable, then run configure again with whatever option you want. It's a good idea to check the weekend before switching, as it will warn you if any of the required dependencies are not available. If this happens, you can either install the dependencies and rerun the setup again, or adjust the call to disable the extensions that need them.

Finally, run NMAKE to start compiling.

Cd C: \ PHP-Dev \ php5.4 buildconf configure nmake nmake test

If any configuration or NMAKE fails, the problem is one of two things: First, the environment is not configured correctly, second, you have enabled a feature that depends on external libraries and the libraries are not installed on your system. Double check that you created the environment according to the instructions above, and that any additional libraries that might be required in the framework have been configured.

When the first NMAKE compilation process is complete you will find your new ones PHP files in the Release_TS folder. The NMAKE test runs new double through-bucket bugs to make sure everything is working as it should. The results of the NMAKE tests are sent to the QA team, which depends on them to improve PHP, so it can take a few minutes to get going, it's a big deal.

At this point, you can also take advantage of the additional NMAKE snap-in step, which will create ZIP archives and binaries to copy around.

Compiling extensions

There are two ways to compile PHP extensions: statically and dynamically. A statically compiled extension is compiled to a PHP binary, while a dynamically compiled one is a separate DLL that can be loaded later via a php.ini file. Extensions are usually compiled according to the state of the DLL, although there are some advantages to static compilation as well, ultimately it depends on your needs.

To compile PHP extensions on Windows, extract the extension source folder into the ext folder, your PHP source directory. Then, re-configure the script by running buildconf - force and recompiling PHP using the appropriate steps to enable the extension.

As an example, let's compile the AOP extension statically. Download the source code from PECL, and unzip it to a folder in ext. Then follow these steps:

Cd C: \ PHP-Dev \ php5.4 buildconf --force configure --enable-aop nmake

With the --force option, buildconf forces it to restore the configuration script. Then, run configure --help and you should see an option to enable the new extension in the output. In this case, it is --enable-AOP.

When nmake finishes ends, you will need a newly built PHP binary with PHP with AOP.

The extensions will be available as a DLL, not baked in PHP, you can follow the same steps as above, but define "shared" as the value to customize, the option allows.

Buildconf --force configure --enable-aop = shared

As a result, the DLL will be in the Release_TS folder along with the PHP binary, the compilation will end, in this case the name is php_aop.dll.

P.S.

Compiling on Windows is still a bit tricky, especially when it comes to extensions. Being able to compile from source is a good skill, especially if you later want to change PHP.

The article was prepared for you, the site team
Original article:
Translated by Victor Klim

Alexey Romanenko: My name is Alexey Romanenko, I work for RBC. The topic of this talk is somewhat controversial. It would seem, why compile PHP scripts when everything seems to work like that?

Probably the main question is: "Why?" In general, the purpose of this presentation is to try to understand whether such a compilation is needed, if so, why, in what form and to whom.

What is a PHP compiler?

First, a little overview of what a PHP compiler is. I'll tell you how it works, what it is and how you can speed it up.

The first functional module is the so-called SAPI (Server API), which provides an interface for accessing PHP from various clients (Apache, some kind of CGI server (Common Gateway Interface), and others). There is also SAPI embedded, which allows you to embed PHP into any application.

The second main part is PHP Core, which handles requests, implements all networking, file system and by parsing the scripts themselves.

The third global part is Zend Engine, which compiles our scripts into some bytecode, executes it on its virtual machine and deals with memory management (implements comprehensive allocators).

One of the most important and largest parts is the Extentions module, which implements 99% of what we use in PHP. These are either "wrappers" for some libraries, or functionality, or classes, built-in libraries, etc. We can also write our own extensions.

How is the script itself executed?

First. Lexical analysis takes place - the file is loaded, parsed, all symbols from the set of this file are translated into a certain set of tokens, with which we then work.

The parsing phase parses these tokens. Based on this analysis, a certain grammatical structure is compiled, on the basis of which the byte code will be generated later.

At the end, the Zend Engine executes it. The result is sent back to the client.

We are talking about high loads. If you reproduce this scheme of actions every time with them, everything will work very slowly. When several hundred or thousands of requests arrive at our interpreter at the same time, the speed is simply not there.

But there are solutions. They have been known for a long time.

How to achieve acceleration?

The simplest, cheapest and most well-tried solution is bytecode caching. Instead of going through the parsing and parsing phases, we just cache our bytecode. There are special extensions for this - they are well known to everyone who has worked with PHP - these are APC, eAccelerator, Xcache, and so on. Zend Engine just executes bytecode.

The second option is code profiling, identifying bottlenecks. We can rewrite something as PHP extensions (it will be a C / C ++ extension) compile it and use it as modules.

The third option is more global - forget about PHP and rewrite everything. In general, the variant has the right to life, but only in the case when there is not enough php-code. In large, large projects (or those that have existed for quite a long time), it usually accumulates a lot, and it will take a long time to rewrite everything. Business requirements won't let you do this. In general, writing something in PHP, for example, for a front-end server, is not too long, because it is a simple language. It allows you to quickly do things that take longer in low-level languages.

There is Alternative option which has recently become widespread is to compile PHP somewhere, into something faster.

Let's compile something?

By the word "compilation" I mean the translation of the PHP script code into something else, into some other code.

In this case, it can be of two types.

Native code is a kind of binary file that can be executed on a physical machine.

Non-native code. It is possible to compile some bytecode that can be executed on another virtual machine, for example, on the JVM.

What can be used to compile native code from PHP?

Roadsend compiler. Its sequel is Raven. There is also PHC (this is PHP Open Source compiler). Recently, HipHop (Facebook) has also appeared.

Here's a quick overview of what you can do for non-native code. As far as I know, there are 3 working options. This is bytecode generation for Java and bytecode generation for .Net: Quercus, Project Zero, Phalanger. I will not consider compilation into non-native code, because we do not use it. Let's go back to compiling to native code.

In my opinion, the oldest compiler is Roadsend. It began to be developed quite a long time ago, in 2002. This was originally a commercial application. It was closed, only in 2007 it was released into Open Source. There is very complex scheme compilation: a Bigloo compiler for the Scheme language is used, after which the native code is generated. This compiler does not use Zend Engine.

We can either generate a separate executable binary or generate a module for Apache. It is also possible to generate a binary that will act as a web server. But it doesn't work. I don't know why, but it doesn't work for me at all.

As far as I know, Roadsend is not currently being worked on. It was reborn as the Raven project, which was completely rewritten in C ++. As a compilation, it uses LLVM to generate code.

On this moment everything looks very promising.

But it is still at the stage of creation. Even in the documentation there are hints that we will not generate binaries. Wait.

Everything would be sad if we didn't have PHC. It is an OpenSource compiler. It has been in development since 2005. One of its downsides: it uses an embedded SAPI. We are not abandoning the Java machine, the Zend Engine. Basically, it translates PHP code into PHP extension module code. It then compiles, but the execution process again uses the Zend Engine.

Example of using PHC

It is very similar to how we work, for example, with conventional compilers, gcc. The first one shows that there is one binary, we can also just generate the "C" code. Since the same gcc is used internally after generating this code, we can use those flags that are intended for optimization and other things.

It was about an application that runs on the command line.

To launch a web application, you need to perform several steps, it is quite difficult. First, you need to generate an extension (Extention), then compile the code, and then somehow (either dynamically or statically) connect it.

Key benefits of PHC

In fact, we use the same PHP, we have full compatibility. All other extensions are supported. Everything that we have compiled, we use. Pretty good documentation.

By the way, one of the additional bonuses of PHC is that you can generate the XML work of our script based on how the XML is built, sometimes this can be useful.

Minuses

In my opinion, this is an incomplete binary, because it still has a dependency on the Zend Engine. There is also some difficulty in terms of connecting web projects.

The main thing

Probably, this talk would not have happened if HipHop, a solution from Facebook, had not appeared. Its creators also accumulated a large amount of PHP code and thought for a long time what to do with it.

As far as I understand, after the options to rewrite everything were rejected, it was decided to write a translator (in this case, to C ++ code). The project is relatively young; it was officially released only in February of this year. PHP code is translated into C ++ code and then generated using the standard tools of your operating system. True, so far only the Linux operating system is supported.

Just yesterday, I asked a Facebook representative about this decision. He said that at the moment, 100% of the PHP code is compiled through HipHop. V pure form the code does not work through the PHP interpreter. Again, the creators declared a significant reduction in the processor load.

The main functionality of HipHop

It generates directly the binary itself, which can be executed on the command line. There is such an option for launching it as a streaming web server. There is also a separate built-in debugger. They can debug scripts both locally and remotely (it will work as a server).

The build process is pretty nontrivial. There is a description, but it is not collected everywhere. At the moment, as I said, everything is assembled under Linux, plus everything was initially "sharpened" for 64 bits. Although now experimentally 32 bits are supported. But I managed to collect and patch a little - in general, he did all this, because by default it is not going to.

In addition, they have their own versions of libcore and, in my opinion, there are a couple of libraries that also need to be patched. In general, the build process is not that simple.

At the output after the build, we get a certain hphp file, which is a translator of our PHP code into C ++. If we look at flags, there are quite a few of them. I have highlighted here a few basic ones that you may need.

As config file(config) we can use the HDF file by setting various directives. We can set the level of errors and other things there (HDF is everything that is in a structured form). Also, we can take the config itself from the database or use it directly on the command line.

We set the logging level during compilation: show all errors or also display warnings, Additional information, or generally keep a complete log of everything that happens.

A very useful directive is input_list = FILE, which allows us to specify a list of scripts that we want to compile. Also worth mentioning is the lazy-bind directive. We can specify all project files - those that will be compiled.

An example of starting the compilation of a PHP script

The third level of logging has been installed, here it is quite general information by time, you can see how much it took. Actually, the script is pretty simple. This is the usual “Hello, World”, I just took a screenshot.

The "heaviest" file is our "program" binary, its size is 28 MB. In fact, our "Hello, World" weighs in at 28MB. I would like to point out that besides the standard "Echo" Hello, World! "Line, this binary includes a lot more.It is a full-fledged web server, a full-fledged server for administration.

What do we get?

We have "Hello ..." in C ++, which performs a function consisting of one line "echo" Hello, World ". In addition, a lot of third-party things are loaded. As we can see, this is a full-fledged file in C ++.

This is the resulting program. It already contains quite a few different keys for different configurations, but I will only mention a few of them.

This is --mode, this is the launch mode of our program. We can run it either directly (from the command line) or in the mode of a web server or a full-fledged daemon. There are a couple more options, but they are irrelevant.

Used config in the same format. I didn’t give directives because there are a lot of them. Documentation is included with HipHop. It is not on the wiki site, but documentation is provided with the distribution kit, where everything is clearly described. I didn’t even expect that the description would be so detailed. It allows quite flexible configuration of the solution.

To run in server mode, we can specify a port. For administration, a separate port is used, where you can put some requests that allow you to manage the server. If we have a debug server running, then we indicate the host and port where we will "bind" for debugging.

Launch example

For example, we specified port 9999 for broadcasting. By performing simple http requests, we can receive either statistics, or somehow manage the server, or receive some additional information. In general, this is very convenient.

Status option

It is possible to get the server status set in various built-in formats (xml, json, html). In fact, information is provided about the server master process itself and the handlers - the threads that process the requests.

Additional statistics

In fact, a lot of statistics are provided. Since HipHop works natively with memcache and SQL as MySQL, it provides detailed information for all operations that are performed with him.

Full statistics of work with memory

There is very useful feature- Application Stats. Using additional functions HipHop itself in PHP, we can write statistics in our scripts, which we then get through regular access to http.

Debugging

As I said, it is possible to use the built-in "debug" to debug scripts. This is very convenient, because the hphpi interpreter works in a similar way to what we have compiled. There is a difference in the "behavior" of scripts when they are executed in standard PHP and when using some data from the compiled ones. To debug what is compiled, Facebook wrote a separate interpreter.

In the first case, run the code with the “-f” key and see how the file behaves; all output goes to stdout. Or we can run it in debug mode and get into the interactive debugger. It is very similar to standard GDB: you can also set breakpoints, run, enter variable values, track, and more.

One of additional opportunities

We have a program that came out after compilation. It can be used as an RPC server. We launch requests via http, and by calling the params function, we can pass the parameter as either a json array or as a separate parameter. We will have json returned, which returns the results of these functions. It is very convenient - the required functionality is already built in from the outset.

Cons of HipHop

Language constructs and functions such as eval (), create_function () and preg_replace () with / e are not currently supported in HipHop, although they are all analogous to eval (). True, in recent releases, in my opinion, you can still enable eval () via config. But it is not recommended to do so. In general, it is bad to use eval ().

The main advantages of HipHop

Of course, the main plus is the support from Facebook. It works and is developing quite actively. A community of developers is developing around this project. A completely new PHP implementation has been written.

As I said, the plus is that native code is generated. The claimed performance gain by reducing the cost of using the processor (tests confirm this).

It is quite flexible in its configuration. I was pleasantly surprised that there are quite a few options for customization. I think this is due to the fact that the project really works. Everything that is used is incremented.

As I mentioned, HipHop provides quite a few additional features. Among them, use as an RPC server, administration, various statistics and much more. By the way, there is also an API for working with other languages.

Quite good documentation has been written for this solution. Another advantage: it is a solution that is really ready for use in production (example - Facebook).

Minuses

The main disadvantage is that a rather limited number of modules are currently supported. For example, when working with a database, we can only use the functions for working with MySQL. There is no PostgreSQL support here.

There is also such a moment as the complexity of the assembly, which I already mentioned. There are build problems on 32-bit systems. But this, I think, will soon be corrected. So far, only compilation from PHP 5.2 is used. Version 5.3 is not yet supported, but will be supported as promised.

What shouldn't be expected from compilation in general and from HipHop in particular?

Compiling will in no way speed up your slow SQL queries against the database. If bottleneck- this is a base, then compile it or not compile it, there will be no sense from this.

Compilation does not speed up loading statics, only dynamics. It makes debugging much more difficult. Probably, many are used to the fact that everything is debugged in PHP quite simply. When compiled, this will no longer work. Although, as I noted, Facebook made this process as easy as possible, without it it would be even harder to compile every time.

Do not expect that this is some kind of "silver bullet" that will solve all your problems. In fact, compilation solves a fairly narrow range of problems. If they are, then it might help.

What problems does compilation solve?

It reduces the load on the CPU, since when actively working with PHP with a large number of requests, the load on it increases quite strongly. Of course, I would like to conduct some tests.

Testing

The first test (the simplest one) is a rather expensive operation that takes a long time to complete. In the tests, I tried to abstract myself, not to make requests using some external resource.

The load falls entirely on the processor. The test showed that HipHop "won" over everyone: it works almost one and a half times faster than the standard PHP compiler. PHC passed this test very slowly.

For the second performance test, I took the official PHP script that can be downloaded from SVN. It performs a number of functions that perform sorting, assignment, summation - quite expensive operations in terms of mathematics.

HipHop was in the lead again. Moreover, with standard PHP, the time difference is about 3 times. PHC performed better here, but about twice as bad as HipHop.

Mostly PHP is used for streams that handle http requests - this is something to keep in mind.

Several standard configurations(Apache with PHP, Nginx with fpm-php and a pluggable APC for code caching). The fifth option is HipHop.

To be honest, I did not run the tests on a server, but on a laptop. The numbers, of course, may not fully correspond to reality, but in this case the results are normal. It is worth noting that as the load increases, the number of requests and the total number of requests increase simultaneously. Next is RPS. The standard page was tested, which includes 10 of some simple inclusions... Basically, this is testing PHP as an interpreter.

Question from the audience: What are the numbers in a cell - seconds?

Alexey Romanenko: This is fps.

Here we can conclude that with the increase in the number of concurrent requests, HipHop behaves very well.

It can be seen that the use of APC is standard practice. It shows that it adds, for example, as Apache, a performance gain of about 2 times. Nginx has this too. But the fact that Nginx is slow does not mean that this bundle is worse. Just a specific test. If we actually test here, then Apache will "die" on slow requests.

Probably, I want to understand whether we need it or not.

When should you consider compiling?

Most likely, this is necessary in the case when we see that our bottleneck is the CPU. If we "run into" the CPU, using PHP as the standard interpreter, it is probably worth considering that, perhaps, part of the project can be compiled.

For some cases when you need the autonomy of your application to run, this method is unlikely to work.

Reducing the number of servers. When there are a lot of servers, then by halving the performance, roughly speaking, we also halve the number. When it is one server, it makes no sense, but when there are 100-200, then it probably makes sense.

The main reason why Facebook started to use HipHop is the presence of large amounts of PHP code that cannot be rewritten (or there is no one, or is simply expensive). A 2x increase in productivity is already a good thing.

Probably everything. Waiting for questions.

Questions and answers

Question from the audience: Hello. Please tell me if you have any other examples of successful Hiphop implementations besides Facebook. Would you like to transfer the RBC website, for example, to HipHop? Alexey Romanenko: I'll start with the second one. It is difficult to translate the RBC website. About the successful implementation. I compiled PHP Unit myself, it compiled successfully. Also, as far as I know, PHP Bunty board compiles successfully. A number of organizations, in fact, already use compilation. Further tests will show how justified the use of this project will be. Question from the audience: Can you give an example of an organization that uses it? Alexey Romanenko: Honestly, I won't tell you now, but this is the West. As far as I know, nobody uses it here. Question from the audience: What is the difference at runtime other than lack of support for some of the features you mentioned. How dangerous is it to translate a live project? Alexey Romanenko: The difference is that any compiled program can crash. Perhaps some problems will appear that have not yet been identified. In fact, there are a number of differences in the "behavior" of PHP itself. I did not mention them, because more detailed information can be found in the documentation. The Facebook team wrote their own interpreter, which is, in fact, 99.9% equivalent to the one that will work in compiled form. It's better to test your code not with a standard PHP interpreter, but, as I said, hphpi for PHP.

All free PHP compilers that are presented here can rebuild PHP scripts into machine code that can run on a computer without loading a special PHP interpreter, or compile them into a bytecode command line interface (to install, you need NET or Mono framework or Java bytecode (where virtual machine Java for installation)).

Such compilers can be useful for a variety of purposes: they can speed up the execution of your script because they are no longer interpreted at runtime; or thanks to them, you can distribute your applications without revealing the source code (which is required by other commercial scripts). I guess they also work in the case where someone wants to write internet dependent PHP programs and distribute them with a desktop runnable function (as opposed to regular web applications that run on a server), this is all possible because that PHP is an easy-to-learn programming language and, at its core, contains many built-in functions with Internet access. (In this case, you either have to redistribute the applications with an embedded web server, or use a compiler that compiles the server into your application.)

By the way, if you want to use obfuscation in your code, then you should know that this is also possible when using PHP accelerator... These accelerators also offer an increase in the speed of execution of your script.

Useful information for those who do not yet know that official version The PHP translator can be downloaded from the PHP website: Hypertext Processor.

Free PHP compilers for writing native code, .NET or Java bytecode scripts.

Bambalam (new)

This program produces independent Windows applications EXE for your PHP source code. It's not really a compiler for native code as it just encodes the source code and embeds a PHP interpreter, but this program is definitely suitable for people looking for compilers for native and byte-code. By the time the entire program was written, its execution environment was built-in PHP 4.4.4 (the program has not been updated since 2006). The source code for Bambalam is in the public domain.

Phalanger (for .NET)

Phalanger compiles your PHP code to CLI bytecode (.exe or.dll). This program can be run through .NET 4.0 or Mono frameworks. Your PHP code can use any .NET objects and additional libraries standard extension PHP. The resulting NET assembly can be either signed or hidden. This program also releases templates to let you build PHP applications using Visual Studio. The program is released under the Apache license.

HipHop for PHP (for native code)

HipHop translates your PHP code into C ++ code, which is later compiled using the GNU C ++ compiler, into an executable binary code... The compiler supports all the features of PHP 5.3 (of course, except for such a thing as eval ()). It works and compiles code for 64 bit Linux and FreeBSD. Since the program is distributed in source form, you have to compile it manually (yourself). It is released under the PHP License.

Roadsend PHP (for native code).

The Roadsend PHP compiler produces machine binaries (executables) for Windows and Linux. Your scripts are not limited to console programs ( command lines): they can be built with built-in web servers allowing them to work the way they do on a website, even if yours is. custom system... The compiler is released under GNU license GPL and run under the GNU LGPL. Unfortunately, the program stopped its active development.

Project Zero (for Java)

(Note: this software appears to be now defunct. The site has been out of reach for half a year now.) Project Zero includes a compiler and CLR that can compile your PHP code to Java bytecode and execute it. Note that Project Zero is more than just a PHP compiler / runtime; it is an advanced framework that allows you to improve web applications using PHP or Groovy (another scripting language). This compiler is available for Windows, Mac OS X and Linux. In order to work with this compiler, you need to download the Java Development Kit.

Which of the suggested compilers do you prefer? Or do you have another favorite translator? Leave your remarks and comments below, we will gladly read them and rewind them.

Tags: PHP compilers, script translation

PHP is an interpreted programming language, with every request the source code is parsed and "executed". This approach, of course, is very convenient at the stage of project development, but it introduces an extra step in the process of executing production code. Thus, the interpretation at first glance strong point PHP costs extra CPU time and resources.

Below we will talk about compilers that allow you to compile php code in C ++, and its in executable. Thus PHP applications are executed directly by the processor, bypassing the interpreter.

Let's check if everything is so good in practice.

How the interpreter works

There are two steps to interpreting PHP code:

  1. Code parsing and generation of opcodes (Zend opcodes) - instructions that the interpreter understands.
  2. Execution of opcodes.

While the first phase lends itself well to optimization (using the opcode cache), the second is rather closed - the interpreter is always an intermediary between a set of instructions and the processor that executes them. Without an interpreter, the processor cannot figure out what to do with the opcodes.

To get rid of the interpreter link, compilers were invented, the most popular and recent of them is HipHop from Facebook. Let's feel it closer.

HipHop PHP

HipHop is written by the Facebook developers and is an application that:
  1. optimizes PHP code
  2. converts to C ++
  3. generates from your application a multithreaded web server executing it
  4. compiles to executable code using g ++

Thus, the PHP code is input, the server output is a part of which the written functionality is.

Let's check how HipHop can cope with compiling an application written using a framework, such as Wordpress.

Compiling Wordpress

After installing HipHop in the src / hphp / folder, we get the hphp file, which is the compiler. Before starting compilation, we set the environment variables:

Cd .. # go to the folder with hiphop export HPHP_HOME = `pwd` export HPHP_LIB =` pwd` / bin export CMAKE_PREFIX_PATH = `/ bin / pwd` /../

and go!

Download Wordpress and unzip the archive:

Wget http://wordpress.org/latest.tar.gz tar zxvf latest.tar.gz

Copy wp-config-sample.php to wp-config.php and specify the settings for connecting to the database (in the host settings, specify 127.0.0.1, not localhost).

For successful compilation, you need to patch Wordpress a little:

  1. Open wp-includes / js / tinymce / plugins / spellchecker / classes / SpellChecker.php and replace: function & loopback (/ * args .. * /) (return func_get_args ();) with function & loopback (/ * args .. * / ) ($ ret = func_get_args (); return $ ret;)
  2. In wp-includes / query.php, instead of if (! Isset ($ q ["suppress_filters"])) $ q ["suppress_filters"] = false; insert $ q ["suppress_filters"] = true;

Wordpress is ready.

Hiphop "you need to specify a list of files that we will compile - get it and save it to files.list:

Find. -name "* .php"> files.list

Everything is ready for compilation, let's get started:

$ HPHP_HOME / src / hphp / hphp --input-list = files.list -k 1 --log = 3 --force = 1 --cluster-count = 50

After completion of the command execution, in the temporary folder (at the beginning of compilation, hphp will show its path, something like "/ tmp / hphp_ptRgV1") we will get the compiled web server. Let's start it (if on port 80, something hangs, for example apache or nginx - you must first stop to free the port):

Sudo / tmp / hphp_6s0pzd / program -m server -v "Server.SourceRoot =` pwd` "-v" Server.DefaultDocument = index.php "-c $ HPHP_HOME / bin / mime.hdf

Voila! Going to http: // localost will see a working Wordpress blog.

Performance

Let's see if there will be a performance gain compared to the uncompiled version of WordPress running on apache2. Below are graphs of the dependence of the speed of page generation on the number of concurrent users.

As you can see, the results are shocking: the compiled blog runs on average 6 times faster! The average number of processed requests per second in the uncompiled 9, and in the compiled 50! I don’t know about you, but these results amazed me, I didn’t expect such a strong performance increase.

Summarize

After such stunning results, only one thing can be said - the guys from Facebook did their best. The compiler really makes a rocket out of the application, and although the application needs to be prepared before compiling, the result is worth it.

To this topic:

If you liked the post - click on Google +1 - I will be more motivated to write more and just nice.

Programming languages ​​come in two flavors: interpreted and compiled. What language is PHP? In order to answer this question, we need to understand the terminology.

A program that translates code written in one programming language into another is called a translator. A compiler is also a translator. It translates high-level language code into machine code. The compilation process creates a binary executable file that can already be run without a compiler.

The interpreter is a completely different category. The interpreter does not translate the code, but executes it. The interpreter analyzes the program code and executes each line of it. Each time you execute such a code, you must use an interpreter.

In terms of performance, interpreters are significantly inferior to compilers, since binary code is much faster. On the other hand, interpreters allow full control of the program during its execution.

As far as PHP is concerned, it is neither a compiler nor an interpreter. PHP is a cross between a compiler and an interpreter. Let's try to figure it out and see how PHP processes the code.

Consider the picture:

We can see that PHP is composed of two almost independent blocks - a translator and an interpreter. Why did you need to do this? Of course, for performance reasons.

A script is served as input to PHP. It translates (translates) it, checking the syntax, into a special bytecode (internal representation). PHP then executes the bytecode (not the code of the program itself) without creating an executable file.

Bytecode is much more compact than ordinary program code, so it is easier (and faster) to interpret (execute). Judge for yourself: parsing is carried out only once at the translation stage, and the "semi-finished product" is already executed - byte-code, which is much more convenient for these purposes. Therefore, PHP is more of an interpreter than a compiler. This "double work" was necessary for the following purposes.

Consider a loop:

For (i = 0; i<10; i++) { Operator_1; Operator_2; Operator_3; ............ Operator_99; Operator_100; }

This cycle will “spin” 10 times. For each of these ten passes, the interpreter must and 100 lines of code. And in it you need to analyze and execute 10 * 100 = 1000 lines of code! If you translate the entire cycle into bytecode once, then it will have to analyze 10 times less! This means that scripts will run 10 times faster!

It turns out that PHP is.

The main phase of PHP's work is the interpretation of the internal representation of the program and its execution. It is this phase that takes the most time in serious scenarios. However, the slowdown is not that significant.

It is worth remembering that PHP version 3 was a "pure" interpreter, "and since PHP 4, scripts have become much faster to execute, since PHP 4 (and PHP5) is an interpreted translator.

The Perl language, which is almost always called a compiler, works in exactly the same way - it translates the text of the program into an internal representation, and then uses the resulting code at runtime. So you can say PHP version 4 is a compiler just as much as Perl is.

So, we are forced to conclude that PHP is an interpreter with a built-in translation block that optimizes the course of interpretation.

Using an interpreter (and hence PHP) has its undeniable advantages:

  • There is no need to worry about freeing the allocated memory, there is no need to close files when you finish working with them - all routine work will be done by the interpreter, since the program is executed under its vigilant control;
  • You don't need to think about the types of variables, and you also don't need to declare a variable before using it for the first time;
  • Debugging programs and detecting errors are greatly simplified - the interpreter has full control over this process;
  • In the context of web applications, the interpreter also has a very important advantage - there is no danger of the server "freezing" if the program does not work properly.

There are other advantages as well. In general, using an interpreter can give scripts the power that Web users expect from them.

PHP's performance loss is noticeable in the case of large and complex loops, when processing a large number of lines, etc. However, note that this is the only PHP drawback that will appear less and less as more powerful processors come out, so that in the end , generally come to naught.

<<< Назад
(What's new in PHP5?)
Content Forward >>>
(Migrating to PHP 5.3)

If you have any more questions or something is not clear - welcome to our