跳轉到內容

C++ 程式設計作為一系列問題/CGI 指令碼程式

來自 Wikibooks,為開放世界提供開放書籍

簡單指令碼

[編輯 | 編輯原始碼]
/* cgi_hello.cpp
public domain
NB: tested code.
*/
#include <iostream>

using namespace std;

void send_CGI_header(){
    cout << "Content-type: text/html\n";
    cout << "\n"; // this blank line is a necessary part of the CGI protocol.
}
void send_contents(){
    cout << "<!doctype html>\n";
    cout << "<html>\n";
    cout << "<title>Hello</title>\n";
    cout << "<p>Hello, world!\n";
    // C strings can, with care, contain double-quote characters, newlines, etc.
    cout << "<p><a href=\"http://validator.w3.org/check?uri=referer\">";
    cout << "Valid.</a>\n";
    cout << "</html>\n";
    cout << endl;
}

int main(){
    send_CGI_header();
    send_contents();
    return 0;
}

將此原始碼編譯成一個名為“test_script.cgi”的可執行檔案。

幾乎所有 Web 伺服器都支援通用閘道器介面。以下是一些關於如何在 Apache 伺服器上放置用 C++ 編寫的 CGI 指令碼的簡要說明;其他 Web 伺服器類似。有關更多詳細資訊,請參閱 Apache wikibook,第 ... 節,或您最喜歡的 Web 伺服器的類似文件。

... 安全隱患:使用者“nobody”...

CGI 指令碼用於處理表單資料提交。以下是一個示例 HTML 檔案,它允許使用者將資料提交給“test_script.cgi”程式。

<!-- test_form.html -->
<html>
 <form action="test_script.cgi" method="get">
   Favorite animal: <input name="favorite_animal" type="text" />
   <input type="submit" />
 </form>
</html>

將編譯後的“test_script.cgi”放在相應的“cgi-bin”目錄中。將“test_form.html”放在某個方便的位置 - 通常是同一伺服器上的另一個目錄,但它也可以在其他伺服器上或您本地機器上的檔案。調整“action”屬性以給出 CGI 指令碼的路徑。

啟動您最喜歡的 Web 瀏覽器,並將它指向“test_form.html”。單擊提交按鈕。CGI 指令碼的輸出應顯示出來。單擊“有效”連結。

靜態 HTML

[編輯 | 編輯原始碼]

上面的指令碼始終給出相同的輸出 - 如果這確實是您想要的,那麼一個簡單的靜態 HTML 頁面將以更少的努力給出相同的結果。

<!doctype html>
<!-- static_hello.html -->
<html>
<title>Hello</title>
<p>Hello, world!
<p><a href="http://validator.w3.org/check?uri=referer">Good.</a>
</html>

CGI 指令碼的強大之處在於它可以做靜態 HTML 頁面無法做到的事情。

獲取指令碼輸入

[編輯 | 編輯原始碼]

已經有多個庫可用於處理將 CGI 輸入拆分為名稱/值對列表的棘手部分。


/* cgi_hello.cpp
public domain
WARNING: untested code.
*/
...
int main(){
    send_CGI_header();
    send_contents();
    return 0;
}

CGI 指令碼不使用命令列引數“argc”或 argv”。相反,它從環境變數中獲取輸入 - 並且,在 HTTP PUT 或 HTTP POST 的情況下,程式從標準輸入讀取使用者提交的資料。

將此原始碼編譯成一個名為“test_script.cgi”的可執行檔案。使用相同的 test_form.html 來測試它。

進一步閱讀

[編輯 | 編輯原始碼]
華夏公益教科書