首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C/C++ CGI 程序開發入門:從 Apache 配置到調用系統命令

     編輯:關於C++

什麼是 CGI

Common Gateway Interface,HTTP 服務器與外部程序交互的標準接口。程序運行在服務器上,通過標準輸入/輸出、環境變量傳遞數據。

Apache 2.0 配置要點

  1. 確保 IIS 未佔用 80 端口(關閉或更改端口)。
  2. 編輯 httpd.conf:
      取消註釋 AddHandler cgi-script .cgi
      設置 ScriptAlias /cgi-bin/ "路徑/" 並允許 Options ExecCGI
  3. 重啟 Apache,訪問 https://localhost/ 測試。

第一個 CGI 程序 (C++)

#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。

POST 表單處理實例

前端 HTML

命令:

後端 CGI (cmd.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; }

關鍵注意事項

  • CGI 程序必須輸出 Content-type: text/html\n\n 作為 HTTP 響應頭。
  • POST 數據通過標準輸入讀取,長度由環境變量 CONTENT_LENGTH 指定,gets 不安全,實際應用應用 fread(stdin, 1, len, stdin)。
  • Windows 下路徑分隔符、命令執行、臨時文件處理需注意權限。
  • 生產環境極少直接用 C/C++ 寫 CGI,通常用 PHP, Python, Node.js 或 FastCGI/SCGI 協議配合 C++ 後端服務。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved