php-cgi usage example (in C#)

php-cgi usage example (in C#)

RFC 3875 - The Common Gateway Interface (CGI)

PHP Manual: CGI and command line setups


Статья на Хабрахабре (russian)



« Back to Nizarium test page



using System;
using System.Diagnostics;

namespace PhpApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Process php = new Process();

            // Path to php-cgi
            php.StartInfo.FileName = "c:\\php\\php-cgi.exe";
            // We cannot execute it through ShellExecute - need to redirect output stream
            php.StartInfo.UseShellExecute = false;
            // Enable output stream redirection
            php.StartInfo.RedirectStandardOutput = true;
            // Add handler to receive data from output stream
            php.OutputDataReceived += new DataReceivedEventHandler(php_OutputDataReceived);

            // Add only one, the most required for php-cgi environment variable - SCRIPT_FILENAME
            php.StartInfo.EnvironmentVariables.Add("SCRIPT_FILENAME", "test.php");

            // Start php-cgi
            php.Start();
            // Start retrieve data from output stream
            php.BeginOutputReadLine();
            // Wait until php-cgi will stop
            php.WaitForExit();
            // Close php-cgi process
            php.Close();

            // Wait for any key
            Console.ReadKey();
        }

        static void php_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            // If no data received, quit from function
            if (e.Data == null)
                return;

            // Out received data to console
            Console.WriteLine(e.Data);
        }
    }
}