This article is about learning and interpreting readily available code from the internet!
PHP is a relatively popular scripting language that is widely used in web development. The question of how to call PHP within a C++ program without relying on any web server, obtain the execution results, and complete interaction is the functionality that the code in this article aims to achieve.
After installing PHP, there is a `php-cgi.exe` file in the installation directory. We just need to execute this CGI program, pass data to it via named pipes, and then read the execution results through the named pipe. The process isn't complicated! Please refer to the following code:
### Creation of Named Pipes:
```cpp
SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES)};
sa.bInheritHandle = 1;
sa.lpSecurityDescriptor = NULL;
HANDLE hStdoutR, hStdoutW, hStdinR, hStdinW;
CreatePipe(&hStdoutR, &hStdoutW, &sa, 0);
SetHandleInformation(hStdoutR, HANDLE_FLAG_INHERIT, 0);
CreatePipe(&hStdinR, &hStdinW, &sa, 0);
SetHandleInformation(hStdinW, HANDLE_FLAG_INHERIT, 0);
```
### Starting the php-cgi Process:
```cpp
STARTUPINFO si = {sizeof(STARTUPINFO)};
PROCESS_INFORMATION pi;
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdOutput = hStdoutW;
si.hStdInput = hStdinR;
char env[255] = "REQUEST_METHOD=POSTCONTENT_LENGTH=18CONTENT_TYPE=application/x-www-form-urlencodedSCRIPT_FILENAME=D:\\test.php";
if (!CreateProcess(NULL, "d:\\php5\\php-cgi.exe D:\\test.php", NULL, NULL, 1, NORMAL_PRIORITY_CLASS, env, NULL, &si, &pi))
return 0;
CloseHandle(hStdoutW);
CloseHandle(hStdinR);
```
### Passing Data:
```cpp
DWORD dwWritten = 0;
if (!WriteFile(hStdinW, "var=Hello VCKBASE!", 18, &dwWritten, NULL))
return 0;
CloseHandle(hStdinW);
```
### Reading Return Data:
```cpp
char buf[1000] = {0};
DWORD dwRead = 0;
while (ReadFile(hStdoutR, buf, sizeof(buf), &dwRead, NULL) && dwRead != 0) {
printf(buf);
}
CloseHandle(hStdoutR);
```
### Content of `test.php` on Drive D:
```php
```
### Execution Result:
```
X-Powered-By: PHP/5.3.1
Content-type: text/html
Hello VCKBASE!
```
In fact, calling other CGI programs such as PERL from C++ follows a similar method. If you plan to create your own web server, calling CGI programs will be essential.
BTW: How PHP interacts with other applications (such as programs developed in C++) is also an interesting topic. In Tencent's instant messaging software server, PHP interacts with applications through COM components. Friends who are interested can explore this further!
Article URL: [Eden Network](http://www.edenw.com/tech/devdeloper/c/2010-07-15/4709.html)