Execute PHP File Within C#

10 Dec
December 10, 2011

Running PHP from C-Sharp is not a great way to go about building a stable code base, but sometimes it is a necessary evil.

I’ve ran into this very issue recently when trying to convert a new PHP PageRank hashing algorithm into C-Sharp, the problem mainly stemmed from the fact that the code did a lot of Byte Shifting, which is does not map from one programming language to another easily, and so thought I would share my experience regarding how to run PHP code in csharp.

The general issue of having one programming language communicate and interface with another is a very common interoperability problem, with many different solution and approaches depending on the underlying system setup and the nature of that communication we are trying to establish, in this post I present 3 solutions to getting some PHP code to communicate with csharp, some methods are pretty obvious, others are cool but hacky. I leave it to the reader to decide which method they think applies best to their situation.

Run PHP File through C# using Commandline

This is the method I opted-in for, mainly because its so easy and dirty its just amazing.

Fist step you will need to have PHP installed on your machine, follow the instruction and you should be fine.

Next I wrapped my PHP code file in another PHP file that takes input from the command line (using the argv variable), and calls the required function in the main PHP file, using input supplied through the command-line.

<?php

include 'MainFile.php';
// capture command line arguments
$inputArg = $argv[1]; #argument 0 is file name.

//call function in MainFile
$output = MainFile::DoSomething($inputArg);

//write back to the commandline
echo $output;

?>

Next you will need to run the wrapper PHP file from csharp, and capture the commandline output result. You can do this by starting a new .NET Process that executes PHP from the commandline, passing the appropriate arguments to this new Process.

//prepare input
string input = @"some stringy input";

//NOTE: change path according to your own PHP.exe file, if you have the proper environment variables setup, then you can just call PHP.exe directly without the path
string call = @"""c:\Program Files (x86)\PHP\php.exe""";

//To execute the PHP file.
string param1 = @"-f";

//the PHP wrapper class file location. NOTE: remember to enclose in " (quotes) if there is a space in the directory structure.
string param2 = @"""C:\Some Directory\WrapperPHP.php""";

Process myProcess = new Process();

// Start a new instance of this program but specify the 'spawned' version. using the PHP.exe file location as the first argument.
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(call, "spawn");
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;

//Provide the other arguments.
myProcessStartInfo.Arguments = string.Format("{0} {1} {2}", param1, param2, input);
myProcess.StartInfo = myProcessStartInfo;

//Execute the process
myProcess.Start();
StreamReader myStreamReader = myProcess.StandardOutput;

// Read the standard output of the spawned process.
string myString = myStreamReader.ReadLine();

Console.WriteLine(myString);

And voila! You should be able to run the PHP file, providing arguments and capturing output in C Sharp.

Advantage of the PHP to Csharp CommandLine Approach

You can get something up and running extremely quickly.

Disadvantage of the PHP to Csharp CommandLine Approach

Not a strongly typed approach to parameter passing, and not very interoperable.

Capture PHP Output through a C# Web Request

This is a pretty obvious technique, you can wrap your PHP file in a PHP REST web service, this web service can be deployed on Apache or IIS (you will need to download the IIS PHP update in order to deploy it on IIS), your Csharp code will call the PHP web service (using HttpWebRequest or your favorite web request class) with the RESET parameters, the PHP wrapper will consume the data, get the output from running the PHP file, and return the results in the web response, which can be anything from straight text, to HTML, XML or JSON.

You can take this one step further and deploy the PHP code as a SOAP web-service, probably an over-kill, but it does standardize the communication protocol between PHP and C-Sharp, and that has a lot of benefits in an enterprise level architecture.

Advantage of the PHP to Csharp Web Service Approach

Any programming language can take advantage of running this PHP file, which means you massively increase the interoperability of your solution.

Disadvantage of the PHP to Csharp Web Service Approach

Not a quick solution and might require installing additional components in order to get it to work in different environments.

Use Message Queues as an Interoperability Platform between PHP and CSharp

Recently at work we have been getting our teeth dug into enterprise and high-volume communication architecture, and Message Queues is the infrastructure we decided to build this architecture on. In particular, the Active MQ Apache technology.

Message Queues provide a standardized communication interface for sending and receiving messages (or job units), which can be called from many programming languages. Many queuing systems provide an HTTP (or HTTPs) method for receiving and sending messages for maximum interoperability.

Advantage of the PHP to C# Message Queue Approach

Same advantages as wrapping the PHP code in web service, although scales out in a much nicer way; you can essentially have multiple consumers reading from the same queue, and processing in parallel. Very nice way to scale-out your solution.

Disadvantage of the PHP to C# Message Queue Approach

This might require even more setup, in terms of deploying the Message Queue infrastructure as well as writing additional code to interface with the deployed queuing system.

3 replies
  1. Allan says:

    Yeah! This is cool! you saved alot of my time. I was trying to find out how to hash wordpress passwords at once (massive user registration in C#)… The only thing is, I HAVE TO REWRITE THE PHP FILE YOU HAVE PROVIDED. Anyway, THANKS ALOT. yo tha man.

    Reply
  2. KalEljohnDoe says:

    Works Perfect
    Thanks !

    Reply
  3. Dominik says:

    Beautiful! Thank you!

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply to Allan Cancel reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>