一、什么是 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 <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
using namespace std;
using namespace cgicc;
int main ()
{
Cgicc formData;
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>使用 GET 和 POST 方法</title>\n";
cout << "</head>\n";
cout << "<body>\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 << "<br/>\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 << "<br/>\n";
cout << "</body>\n";
cout << "</html>\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