C++进行CGI的WEB编程

一、什么是 CGI

公共网关接口(CGI),是一套标准,定义了信息是如何在 Web 服务器和客户端脚本之间进行交换的。

CGI 规范目前是由 NCSA 维护的,NCSA 定义 CGI 为:

公共网关接口(CGI),是一种用于外部网关程序与信息服务器(如 HTTP 服务器)对接的接口标准。

目前的版本是 CGI/1.1,CGI/1.2 版本正在推进中。

公共网关接口(CGI),是使得应用程序(称为 CGI 程序或 CGI 脚本)能够与 Web 服务器以及客户端进行交互的标准协议。

这些 CGI 程序可以用 Python、PERL、Shell、C 或 C++ 等进行编写

二、CGI程序开发

1、安装apache

sudo yum install httpd httpd-dev

2、安装cgicc库

wget http://ftp.gnu.org/gnu/cgicc/cgicc-3.2.16.tar.gz
tar zxvf cgicc-3.2.16.tar.gz
cd cgicc-3.2.16
./configuer
make
sudo make install

注意:libcgicc.so 和libcgicc.a库会被安装到/usr/lib目录下,需执行拷贝命令:
   sudo cp /usr/lib/libcgicc.* /usr/lib64/
才能使CGI程序自动找到libcgicc.so动态链接库。

3、编写测试程序

#include 
#include   
#include   
#include   
#include 
#include 
#include 
#include 
#include   
using namespace std;
using namespace cgicc;

int main ()
{
   Cgicc formData;
   
   cout << "Content-type:text/html\r\n\r\n";
   cout << "\n";
   cout << "\n";
   cout << "使用 GET 和 POST 方法\n";
   cout << "\n";
   cout << "\n";

   form_iterator fi = formData.getElement("first_name");  
   if(!fi->isEmpty() && fi != (*formData).end()) {  
      cout << "名:" << **fi << endl;  
   }else{
      cout << "No text entered for first name" << endl;  
   }
   cout << "
\n";    fi = formData.getElement("last_name");      if(!fi->isEmpty() &&fi != (*formData).end()) {         cout << "姓:" << **fi << endl;      }else{       cout << "No text entered for last name" << endl;      }    cout << "
\n";    cout << "\n";    cout << "\n";        return 0; }

4、编译程序

g++ -I/usr/include -L/usr/lib -lcgicc -o main.cgi main.cpp
sudo cp ./main.cgi /var/www/cgi-bin/

5、生成 main.cgi,并把它放在 CGI 目录中

并尝试使用下面的链接进行访问:

http://localhost/cgi-bin/main.cgi?first_name=ZARA&last_name=ALI

这会浏览器会输出以下结果:
名:ZARA
姓:ALI

你可能感兴趣的:(C,Plus,Plus)