Sunday, July 6, 2008

How to execute a C# program using PHP

There are many situations where u may want to call another program from the system once a particular condition/requirement is done in a web application.
For instance, I have a web interface in php for the user to send messages through a mobile phone. Unfortunately I dont have a script in php that could send a command to the SMS gateway to send the message i wanted.

I have a C# program which can send messages through mobile phone using a third party library. Here is what i did...
First set the program for sending messages as a program that will take arguements from the command line.
Lets say my C# program name is "sendmessage.c" In the main method of the program
main(string args[]) should be there.
Once the program is compiled,I shall go to the location where the ".exe" file of the same program is present.
In the command line i shall type sendmessage recepient_number message; The program gets executed and the message will be sent.

Now i shall take all the files present in the folder where ".exe" file is present and then transfer them to the folder where .php file is present.
Now in the php scrypt i shall write the following statements:
$command= "sendmessage recepient_number message";

exec($command,$return_var);

The exec will execute the c# code from the command line.
The output of the program (the out put u want to be displayed on console) will be returned in the form of a string array to the variable $return_var.
The values of $return_var can be further used for processing the request in php scrypt(Lets say whether the message was sent successfully to the code..
Whether the program was executed..etc);
Blogged with the Flock Browser