如何使用C++ CGI脚本?

Joh*_*rad 6 html c++ cgi

我目前正在我的大学注册一个Web应用程序课程,我们正在学习cgi脚本.我很难学习如何实现我的CGI脚本.当我点击我的链接时会弹出一个窗口,要求我下载helloworld.cgi文件而不是重定向.

HTML:

<html>
    <body>
        <a href="/user/local/apache2/cgi-bin/helloworld.cgi">click me</a>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

C++:

#include <iostream>

using namespace std;

int main(){
    cout << "Content-type: text/html" << endl;
    cout << "<html>" << endl;
    cout << "   <body>" << endl;
    cout << "       Hello World!" << endl;
    cout << "   </body>" << endl;
    cout << "</html>" << endl;

    return 0;
    }
Run Code Online (Sandbox Code Playgroud)

CGI脚本存储在 /user/local/apache2/cgi-bin/helloworld.cgi

Lou*_*nco 13

您需要编译C++文件,并调用结果helloworld.cgi.C++不是脚本语言 - 您不能只将它部署到您的服务器上.

在典型的*nix系统上,将C++文件命名为helloworld.cpp

 gcc -o helloworld.cgi helloworld.cpp
Run Code Online (Sandbox Code Playgroud)

然后将该文件放在cgi-bin中

编辑:你需要在最后一个标题项后面有两个endl

  cout << "Content-type: text/html" << endl << endl;
Run Code Online (Sandbox Code Playgroud)


cas*_*nca 7

/user/local/apache2/cgi-bin/helloworld.cgi是硬盘上文件的物理路径.要通过Apache运行脚本,您需要指定相对于服务器文档根目录的路径,例如.http://localhost/cgi-bin/helloworld.cgi.