Common Gateway Interface,HTTP 服務器與外部程序交互的標準接口。程序運行在服務器上,通過標準輸入/輸出、環境變量傳遞數據。
httpd.conf:AddHandler cgi-script .cgiScriptAlias /cgi-bin/ "路徑/" 並允許 Options ExecCGIhttps://localhost/ 測試。#include
int main() {
printf("Content-type: text/html\n\n"); // 必須的 HTTP 頭
printf("Hello World! 我是 CGI\n");
return 0;
}
編譯為 hello.exe,重命名為 hello.cgi 放入 cgi-bin 目錄,瀏覽器訪問 https://localhost/cgi-bin/hello.cgi。
#include
#include
#include
#include
void exec_cmd(char* post_data) {
char* eq = strchr(post_data, '=');
if (eq) post_data = eq + 1; // 取值部分
printf("命令: %s
\n", post_data);
char cmd[256], file[] = "temp.txt";
sprintf(cmd, "%s > %s", post_data, file);
if (system(cmd)) { printf("命令錯誤
"); return; }
FILE* fp = fopen(file, "r");
if (!fp) { printf("無輸出
"); return; }
int ch;
while ((ch = fgetc(fp)) != EOF) {
if (ch == '\n') printf("
\n");
else if (ch == ' ') printf(" ");
else putchar(ch);
}
fclose(fp); remove(file);
}
int main() {
printf("Content-type: text/html\n\n");
char post[256] = "";
gets(post); // 讀取 POST 數據(需注意 CONTENT_LENGTH)
if (strlen(post) == 0) strcpy(post, "ipconfig");
exec_cmd(post);
return 0;
}
Content-type: text/html\n\n 作為 HTTP 響應頭。CONTENT_LENGTH 指定,gets 不安全,實際應用應用 fread(stdin, 1, len, stdin)。