How to run dotnet application with PHP in Linux or Windows

How to run dotnet application with PHP in Linux or Windows

Sometimes we don’t want to keep any function or source code human-readable in PHP, in all those cases we can create a .net executable file and, we can run a dotnet application with PHP and use the outputs.

How to create a dotnet console application

At first, we need to create a dotnet project. We have created a Hello World console application project below in Visual Studio 2022. We have used here dotnet version 8.

Here we have printed “Hello World” into the Main() function by using Console.WriteLine() to display output. We have also tried to print 1st argument if anyone provides it as an input.

Then we need to publish it as an executable file from Menu => Build => Publish Selection. Here we have built in linux-x64 application to run the application in a Linux hosting environment.

Publish Dotnet Application with Sefl-contained deployment mode

How to run dotnet application with PHP

To run an executable file or command PHP provides shell_exec function. So let’s upload the Linux application to a Linux hosting environment and provide 0777 permission. If you using a Windows hosting environment then you just need to build the application in win-x64 or win-x86 runtime. The PHP shell execution command will be the same as Linux and Windows.

Here we have uploaded the executable file and set 0777 ( rwxrwxrwx) permission. It means read, write, and execute permission. we have created an index.php to run it by PHP.

How to set file permissions

Example a PHP code to execute an executable file.

<?php 
$output= shell_exec("./TestApp");

echo $output;

We can also pass input as arguments while the command to make an interactive function with PHP. Like shell_exec(“ExecutablePath Arguments”)

After run the dotnet application with PHP shell_exec Output

After run dotnet application with PHP shell_exec Output

Hope the article was helpful for you. If you have any confusion or face any difficulty, you can write a comment below or contact us. Thank you for staying with us.

Leave a Reply

Your email address will not be published. Required fields are marked *

Stay with us to get updated. OK No thanks