How To Use C++ CGI Script?

2020-06-18 04:47发布

I am currently enrolled in a web applications class at my college and we are learning about cgi scripts. I am having a hard time learning how to implement my CGI script. When I click on my link a window pops up asking me to download my helloworld.cgi file instead of just redirecting.

HTML:

<html>
    <body>
        <a href="/user/local/apache2/cgi-bin/helloworld.cgi">click me</a>
    </body>
</html>

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;
    }

The CGI script is stored at /user/local/apache2/cgi-bin/helloworld.cgi

标签: c++ html cgi
4条回答
不美不萌又怎样
2楼-- · 2020-06-18 05:01

/user/local/apache2/cgi-bin/helloworld.cgi is the physical path of the file on your hard disk. To run the script through Apache, you need to specify the path relative to your server's document root, for eg. http://localhost/cgi-bin/helloworld.cgi.

查看更多
走好不送
3楼-- · 2020-06-18 05:05

You need to compile the C++ file, and call the result helloworld.cgi. C++ is not a scripting language -- you can't just deploy it to your server.

On a typical *nix system, name the C++ file helloworld.cpp

 gcc -o helloworld.cgi helloworld.cpp

Then put that file in your cgi-bin

Edit: you need two endl's after the last header item

  cout << "Content-type: text/html" << endl << endl;
查看更多
叼着烟拽天下
4楼-- · 2020-06-18 05:05

You just need to configure Apache to recognise a cgi-bin properly...

Have a read of this: http://httpd.apache.org/docs/1.3/howto/cgi.html

In Apache config ScriptAlias is probably what you want.

(I'm assuming you've compiled the binary to helloworld.cgi)

查看更多
乱世女痞
5楼-- · 2020-06-18 05:09

I had this problem too, and this solution worked for me :
First run this commands on terminal:

sudo a2enmod cgi
sudo service apache2 restart

Then copy helloworld.cgi to /usr/lib/cgi-bin/

sudo cp helloworld.cgi /usr/lib/cgi-bin/

And finally change href link to:

  <a href="/cgi-bin/helloworld.cgi">click me</a>
查看更多
登录 后发表回答