主题:C++调用PHP
[url=http://www.cpbdqn.com]网络工程师培训[/url]
本文由http//:www.cpbdqn.com整理编辑
PHP是比较流行的脚本语言,WEB开发使用广泛,如何在C++程序中不依赖任何WEB SERVER调用PHP,并取得执行结果完成交互,这是本文代码所要实现的功能。
PHP安装好后,在目录下有一个php-cgi.exe,我们只要执行这个CGI程序,并将数据通过命名管道传递给它,然后把执行结果通过命名管道读取出来即可,过程并不复杂!请看如下代码:
命名管道的创建:
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);
启动php-cgi进程: STARTUPINFO si = {sizeof(STARTUPINFO)};
PROCESS_INFORMATION pi;
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdOutput = hStdoutW;
si.hStdInput = hStdinR;
char env[255] = "REQUEST_METHOD=POST\0CONTENT_LENGTH=18\0CONTENT_TYPE=
application/x-www-form-urlencoded\0SCRIPT_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);
传递数据:if(!WriteFile(hStdinW, "var=Hello VCKBASE!", 18, &dwWritten, NULL))
return 0;
CloseHandle(hStdinW);
读取返回数据:char buf[1000] = {0};
DWORD dwRead = 0;
while(ReadFile(hStdoutR, buf, sizeof(buf), &dwRead, NULL) && dwRead != 0){
printf(buf);
}
CloseHandle(hStdoutR);
D盘的test.php
<?
echo $_REQUEST["var"];
?>
执行结果:
X-Powered-By: PHP/5.3.1
Content-type: text/html
Hello VCKBASE!
本文由http//:www.cpbdqn.com整理编辑
PHP是比较流行的脚本语言,WEB开发使用广泛,如何在C++程序中不依赖任何WEB SERVER调用PHP,并取得执行结果完成交互,这是本文代码所要实现的功能。
PHP安装好后,在目录下有一个php-cgi.exe,我们只要执行这个CGI程序,并将数据通过命名管道传递给它,然后把执行结果通过命名管道读取出来即可,过程并不复杂!请看如下代码:
命名管道的创建:
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);
启动php-cgi进程: STARTUPINFO si = {sizeof(STARTUPINFO)};
PROCESS_INFORMATION pi;
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdOutput = hStdoutW;
si.hStdInput = hStdinR;
char env[255] = "REQUEST_METHOD=POST\0CONTENT_LENGTH=18\0CONTENT_TYPE=
application/x-www-form-urlencoded\0SCRIPT_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);
传递数据:if(!WriteFile(hStdinW, "var=Hello VCKBASE!", 18, &dwWritten, NULL))
return 0;
CloseHandle(hStdinW);
读取返回数据:char buf[1000] = {0};
DWORD dwRead = 0;
while(ReadFile(hStdoutR, buf, sizeof(buf), &dwRead, NULL) && dwRead != 0){
printf(buf);
}
CloseHandle(hStdoutR);
D盘的test.php
<?
echo $_REQUEST["var"];
?>
执行结果:
X-Powered-By: PHP/5.3.1
Content-type: text/html
Hello VCKBASE!