Introduction
Usually, running a PHP script in .NET involves shelling to the OS and piping the response back. With Serhiy Perevoznyk's PHP4Delphi, Delphi developers were able to utilize the Zend (PHP) engine without having to resort to the shell. Serhiy created an unmanaged DLL you can call from .NET to reap the benefits of using a scripting engine. If you are a Delphi developer, the full source of the wrapper is available from SourceForge under the PHP4Delphi project.
Background
If you are not familiar with PHP, it is a very popular web scripting language, similar to Perl and Python. Like those languages also, it has applications for the desktop as well as for the web.
This wrapper builds on the PHP engine, providing an interface to the php4ts.dll (for PHP version 4) or php5ts.dll. You will need this file in order to use the php4apps.dll. I included this file in the demo download, but the freshest version is available from the PHP project site.
Using the code
There are seven methods exposed in the wrapper DLL:
InitRequest
- Initializes the engine.
ExecutePHP
- Calls the engine with a file to run.
ExecuteCode
- Calls the engine with a string to run.
GetResultText
- Retrieves the result of the script from the engine.
RegisterVariable
- Registers a variable with the engine, allowing you to retrieve the value later.
GetVariable
- Retrieves the value of a registered variable after the engine has completed.
DoneRequest
- Finalizes the engine.
A simple method to execute a file looks like this:
int RequestID = InitRequest();
ExecutePHP(RequestID, openFileDialog1.FileName);
StringBuilder builder = new StringBuilder();
builder.Capacity = GetResultText(RequestID, builder, 0);
GetResultText(RequestID, builder, builder.Capacity + 1);
DoneRequest(RequestID);
Similar to this, evaluating a string would be just a replacement of the ExecutePHP
method for the ExecuteCode
method:
...
string code = "phpInfo();";
ExecuteCode(RequestID, code);
...
Notice that you did not need the <? ?>
around the PHP code. You could include it if you wish.
Now, the interesting part comes when you can inject your own variables and retrieve the results. If the PHP code looks something like this:
$i="Hello ".$i;
print $i;
and if you want to change the value of $i
without having to append your values to the script, you can do it with RegisterVariable
to set the variable before execution:
string code = "$i=\"Hello \".$i; print $i;";
int RequestID = InitRequest();
ExecuteCode(RequestID, code);
RegisterVariable(RequestID, "i", "World!");
Now the result will be the requisite "Hello World!" To retrieve the value of $i
from the engine, you only need to call GetVariable
.
StringBuilder resultVariable = new StringBuilder();
resultVariable.Capacity = GetVariable(RequestID, "i", resultVariable, 0);
GetVariable(RequestID, "i", resultVariable, resultVariable.Capacity+1);
History