Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Running PHP Applications on .NET Core

DZone's Guide to

Running PHP Applications on .NET Core

Curious about running PHP applications using .NET Core as its platform? In this post we take a look at how you can make this happen!

· Web Dev Zone ·
Free Resource

Learn how Crafter’s Git-based content management system is reinventing modern digital experiences. Download this white paper now. 

Ever wondered about mixing up the simplicity and flexibility of PHP with the power and performance of .NET Core? The solution is coming and it is called Peachpie, the successor of Phalanger. This blog post introduces Peachpie – the tool to compile PHP code to .NET Core – and helps you to get started with it.

Peachpie

Why Peachpie?

For years there was a thing called Phalanger that lived a silent life somewhere on the internet. At least it didn’t make its way to my work desk. Now, years later, it is reincarnated as Peachpie and now it looks really promising. Peachpie allows us to build and run PHP code on .NET Core. For example, they made WordPress run on .NET Core (fairly successfully).

Important! Peachpie is not about writing .NET code using PHP. Peachpie is about running PHP code on .NET.

Is there any point to a solution like this business wise? It looks very promising if full PHP compilation starts working in the near future. The question is not the benefits of using Peachpie and Visual Studio tooling. The question is what we get when building PHP code in .NET Core and run it as compiled code. The answer is simple: take a look at Peachpie benchmarks!

Getting Started

Peachpie is easy to install. All we need is the .NET utility that comes with .NET Core. Open your command line and run the following commands:


mkdir MyWebSite1
dotnet new -i Peachpie.Templates::*
dotnet new peachpie-web
cd MyWebsite1.Server
dotnet restore
dotnet run

If MS Build reports errors then open the project file in your MyWebSite1 folder (not MyWebSite1.Server) and comment out the following line at the end of the file.


<Import Project="$(CSharpDesignTimeTargetsPath)" />

After this, the application should build and run without errors. This is how a Peachpie solution is created, built, and run fully on the command line.

Peachpie Solution

Peachpie solution in Visual StudioWhen running with .NET utility, Peachpie creates a solution that can be opened in Visual Studio. There are two projects (I created a solution folder called 'phpnet' and this is why my solution is named as phpnet):

  • phpnet – this project hosts all PHP files that make up my PHP solution.
  • phpnet.Server – this project is for building and running my PHP solution.

The program.cs file is interesting one. It contains Program and Startup classes, as both classes are very small in this sample application. An assembly of code built with PHP files is included very nicely in the Configure() method of the Startup class.


public void Configure(IApplicationBuilder app)
{
    app.UseSession();       

    app.UsePhp(new PhpRequestOptions(scriptAssemblyName: "phpnet"));
    app.UseDefaultFiles();
    app.UseStaticFiles();
}

Those of my readers who come up with serious questions at conferences want to ask: what happens when I add MVC to the solution?

Adding ASP.NET Core MVC to PHP Solution

Although I don’t see much point in doing this, we can actually use ASP.NET Core MVC the same was we used PHP to get a solution. As NuGet has issues with adding and updating packages in PHP solutions, I had to modify my phpnet.Server project file manually. This is what the NuGet packages section looks like in my project file.


<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.2" />
  <PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.2" />
  <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.2" />
  <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3" />
  <PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="1.1.2" />
  <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="1.1.2" />
  <PackageReference Include="Peachpie.NETCore.Web" Version="0.7.0-*" />
</ItemGroup>

I restored packages from the command line after the change and got no errors. After this, I added MVC to the request pipeline.


class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Adds a default in-memory implementation of IDistributedCache.
        services.AddDistributedMemoryCache();           services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromMinutes(30);
            options.CookieHttpOnly = true;
        });           services.AddMvc();
    }       public void Configure(IApplicationBuilder app)
    {
        app.UseSession();           app.UsePhp(new PhpRequestOptions(scriptAssemblyName: "phpnet"));
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
        app.UseDefaultFiles();
        app.UseStaticFiles();
    }
}

I built the solution and ran it. The following screenshot shows the results.

Peachpie: PHP and ASP.NET Core MVC in same application

This good conference crowd wants to know now one more thing. What happens when MVC is added to the request pipeline before PHP? It can be easily done, and, in this case, MVC processes the request first. If the application root is requested, then “Hello from ASP.NET!” is shown. When index.php is requested, then “Hello from PHP” is shown. So, Peachpie also knows about the PHP file names that were used in the PHP solution.

I didn’t find much information about .NET Core and PHP interoperability and therefore I don’t know to what point it is currently possible. I’m sure they will provide interoperability in the future, as it opens one new option: handing execution over to .NET code in some points of the code.

Decompiling Compiled PHP Code

Using dotPeek by JetBrains, it is possible to decompile .NET executables. I opened my phpnet.dll file from the bin folder of my web application and decompiled the index_php class. This is what the compiler produced from my PHP.

Peachpie: PHP code compiled to .NET

Using dotPeek we can also see IL code of this class.

Peachpie: Compiled PHP code in IL

Using dotPeek, it is also possible to explore the contents of other libraries.

WordPress Example

Peachpie uses their version of WordPress as an example of PHP compilation to .NET. Here is how to set it up.

  1. Download the project from https://github.com/iolevel/peachpie-wordpress
  2. Extract files to some folder.
  3. Install MySQL if you don’t have one to use and run it.
  4. Change database connection settings in wp-config.php.
  5. Open the command line and go to the folder where you copied WordPress project files.
  6. Run the following commands: dotnet restorecd appdotnet run.
  7. Wait a few minutes until the application is compiled and started.
  8. Open http://localhost:5004 in your favorite web browser.

If everything went okay and there are no unexpected issues you should be able to see WordPress running in your browser. Don’t be surprised if you face problems – this is on-going work you are playing with.

Wrapping Up

Peachpie is an interesting project. PHP code is translated and compiled to .NET Core and then run on .NET runtime. Although the project is in alpha right now it looks very promising. Especially when you look at current benchmarks where it is compared to Zend. It would be a good fit for cloud environments where PHP applications get high work loads by customers, for example. It is not very clear from the documentation how we can bridge PHP and .NET Core code but I hope that Peachpie offers something for this in future. I think it is worth keeping an eye on the Peachpie project and to try out what benefits it gives to the PHP applications we currently build and manage.

Resources

Crafter CMS is a modern Git-based platform for building innovative websites and content-rich digital experiences. Download this white paper now.

Topics:
.net core ,php ,web dev ,wordpress

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}