Cplusplus 简明教程
C++ Web Programming
What is CGI?
-
The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script.
-
The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows −
-
The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.
-
The current version is CGI/1.1 and CGI/1.2 is under progress.
Web Browsing
要理解 CGI 的概念,让我们看看当我们单击超链接来浏览特定网页或 URL 时会发生什么。
To understand the concept of CGI, let’s see what happens when we click a hyperlink to browse a particular web page or URL.
-
Your browser contacts the HTTP web server and demand for the URL ie. filename.
-
Web Server will parse the URL and will look for the filename. If it finds requested file then web server sends that file back to the browser otherwise sends an error message indicating that you have requested a wrong file.
-
Web browser takes response from web server and displays either the received file or error message based on the received response.
然而,可以将 HTTP 服务器设置为这样一种方式:每当请求某个目录中的文件时,该文件不会被发回,而是以程序形式被执行,程序产生的输出会被发回您的浏览器显示。
However, it is possible to set up the HTTP server in such a way that whenever a file in a certain directory is requested, that file is not sent back; instead it is executed as a program, and produced output from the program is sent back to your browser to display.
通用网关接口 (CGI) 是一种标准协议,能使应用程序(称为 CGI 程序或 CGI 脚本)与 Web 服务器和客户端进行交互。这些 CGI 程序可以用 Python、PERL、Shell、C 或 C++ 等语言编写。
The Common Gateway Interface (CGI) is a standard protocol for enabling applications (called CGI programs or CGI scripts) to interact with Web servers and with clients. These CGI programs can be a written in Python, PERL, Shell, C or C++ etc.
CGI Architecture Diagram
以下简单程序展示了 CGI 的一种简单的架构:
The following simple program shows a simple architecture of CGI −
Web Server Configuration
在开始使用 CGI 编程之前,请确保您的 Web 服务器支持 CGI,并且将其配置为处理 CGI 程序。所有将由 HTTP 服务器执行的 CGI 程序都存储在一个预先配置的目录中。这个目录称为 CGI 目录,按惯例将其命名为 /var/www/cgi-bin。按惯例,CGI 文件的扩展名为 .cgi ,尽管它们是 C++ 可执行文件。
Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI directory and by convention it is named as /var/www/cgi-bin. By convention CGI files will have extension as .cgi, though they are C++ executable.
默认情况下,Apache Web 服务器被配置为在 /var/www/cgi-bin 中运行 CGI 程序。如果您想指定任何其他目录来运行您的 CGI 脚本,您可以修改 httpd.conf 文件中的以下部分:
By default, Apache Web Server is configured to run CGI programs in /var/www/cgi-bin. If you want to specify any other directory to run your CGI scripts, you can modify the following section in the httpd.conf file −
<Directory "/var/www/cgi-bin">
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
</Directory>
<Directory "/var/www/cgi-bin">
Options All
</Directory>
在这里,我假设您已成功启动并运行 Web 服务器,并且您能够运行任何其他 CGI 程序,例如 Perl 或 Shell 等。
Here, I assume that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell etc.
First CGI Program
考虑以下 C++ 程序内容:
Consider the following C++ Program content −
#include <iostream>
using namespace std;
int main () {
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Hello World - First CGI Program</title>\n";
cout << "</head>\n";
cout << "<body>\n";
cout << "<h2>Hello World! This is my first CGI program</h2>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
编译以上代码并命名可执行文件为 cplusplus.cgi。此文件存储在 /var/www/cgi-bin 目录中且具有以下内容。在运行您的 CGI 程序之前,请确保您使用 chmod 755 cplusplus.cgi UNIX 命令更改了此文件的模式以使其可执行。
Compile above code and name the executable as cplusplus.cgi. This file is being kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program make sure you have change mode of file using chmod 755 cplusplus.cgi UNIX command to make file executable.
My First CGI program
上述 C 程序是一个简单的程序,用于在 STDOUT 文件(即屏幕)上写入其输出。这里有一个重要的额外功能:第一行打印 Content-type:text/html\r\n\r\n 。此行发回浏览器,并指定要在浏览器屏幕上显示的内容类型。现在您一定理解了 CGI 的基本概念,并且可以使用 Python 编写很多复杂的 CGI 程序。C CGI 程序可以与任何其他外部系统(如 RDBMS)交互以交换信息。
The above C program is a simple program which is writing its output on STDOUT file i.e. screen. There is one important and extra feature available which is first line printing Content-type:text/html\r\n\r\n. This line is sent back to the browser and specify the content type to be displayed on the browser screen. Now you must have understood the basic concept of CGI and you can write many complicated CGI programs using Python. A C CGI program can interact with any other external system, such as RDBMS, to exchange information.
HTTP Header
行 Content-type:text/html\r\n\r\n 是 HTTP 标头的一部分,它被发送至浏览器以理解内容。所有 HTTP 标头都将采用以下形式:
The line Content-type:text/html\r\n\r\n is a part of HTTP header, which is sent to the browser to understand the content. All the HTTP header will be in the following form −
HTTP Field Name: Field Content
For Example
Content-type: text/html\r\n\r\n
有其他一些重要的 HTTP 头信息,您将在 CGI 编程中经常使用。
There are few other important HTTP headers, which you will use frequently in your CGI Programming.
Sr.No |
Header & Description |
1 |
Content-type: A MIME string defining the format of the file being returned. Example is Content-type:text/html. |
2 |
Expires: Date The date the information becomes invalid. This should be used by the browser to decide when a page needs to be refreshed. A valid date string should be in the format 01 Jan 1998 12:00:00 GMT. |
3 |
Location: URL The URL that should be returned instead of the URL requested. You can use this filed to redirect a request to any file. |
4 |
Last-modified: Date The date of last modification of the resource. |
5 |
Content-length: N The length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file. |
6 |
Set-Cookie: String Set the cookie passed through the string. |
CGI Environment Variables
所有 CGI 程序都将能够访问以下环境变量。这些变量在编写任何 CGI 程序时发挥着重要作用。
All the CGI program will have access to the following environment variables. These variables play an important role while writing any CGI program.
Sr.No |
Variable Name & Description |
1 |
CONTENT_TYPE The data type of the content, used when the client is sending attached content to the server. For example file upload etc. |
2 |
CONTENT_LENGTH The length of the query information that is available only for POST requests. |
3 |
HTTP_COOKIE Returns the set cookies in the form of key & value pair. |
4 |
HTTP_USER_AGENT The User-Agent request-header field contains information about the user agent originating the request. It is a name of the web browser. |
5 |
PATH_INFO The path for the CGI script. |
6 |
QUERY_STRING The URL-encoded information that is sent with GET method request. |
7 |
REMOTE_ADDR The IP address of the remote host making the request. This can be useful for logging or for authentication purpose. |
8 |
REMOTE_HOST The fully qualified name of the host making the request. If this information is not available then REMOTE_ADDR can be used to get IR address. |
9 |
REQUEST_METHOD The method used to make the request. The most common methods are GET and POST. |
10 |
SCRIPT_FILENAME The full path to the CGI script. |
11 |
SCRIPT_NAME The name of the CGI script. |
12 |
SERVER_NAME The server’s hostname or IP Address. |
13 |
SERVER_SOFTWARE The name and version of the software the server is running. |
以下是列出所有 CGI 变量的小型 CGI 程序。
Here is small CGI program to list out all the CGI variables.
#include <iostream>
#include <stdlib.h>
using namespace std;
const string ENV[ 24 ] = {
"COMSPEC", "DOCUMENT_ROOT", "GATEWAY_INTERFACE",
"HTTP_ACCEPT", "HTTP_ACCEPT_ENCODING",
"HTTP_ACCEPT_LANGUAGE", "HTTP_CONNECTION",
"HTTP_HOST", "HTTP_USER_AGENT", "PATH",
"QUERY_STRING", "REMOTE_ADDR", "REMOTE_PORT",
"REQUEST_METHOD", "REQUEST_URI", "SCRIPT_FILENAME",
"SCRIPT_NAME", "SERVER_ADDR", "SERVER_ADMIN",
"SERVER_NAME","SERVER_PORT","SERVER_PROTOCOL",
"SERVER_SIGNATURE","SERVER_SOFTWARE" };
int main () {
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>CGI Environment Variables</title>\n";
cout << "</head>\n";
cout << "<body>\n";
cout << "<table border = \"0\" cellspacing = \"2\">";
for ( int i = 0; i < 24; i++ ) {
cout << "<tr><td>" << ENV[ i ] << "</td><td>";
// attempt to retrieve value of environment variable
char *value = getenv( ENV[ i ].c_str() );
if ( value != 0 ) {
cout << value;
} else {
cout << "Environment variable does not exist.";
}
cout << "</td></tr>\n";
}
cout << "</table><\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
C++ CGI Library
对于实际示例,您需要通过 CGI 程序来完成许多操作。有一个专为 C++ 程序编写的 CGI 库,您可以从 ftp://ftp.gnu.org/gnu/cgicc/ 下载,并按照步骤安装该库 −
For real examples, you would need to do many operations by your CGI program. There is a CGI library written for C++ program which you can download from ftp://ftp.gnu.org/gnu/cgicc/ and follow the steps to install the library −
$tar xzf cgicc-X.X.X.tar.gz
$cd cgicc-X.X.X/
$./configure --prefix=/usr
$make
$make install
您可以查看 ‘C++ CGI Lib Documentation 上提供的相关文档。
You can check related documentation available at ‘C++ CGI Lib Documentation.
GET and POST Methods
您肯定遇到过许多情况,需要从浏览器向 Web 服务器传递一些信息,并最终传递给您的 CGI 程序。最常见的是浏览器使用两种方法将此信息传递到 Web 服务器。这些方法是 GET 方法和 POST 方法。
You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your CGI Program. Most frequently browser uses two methods to pass this information to web server. These methods are GET Method and POST Method.
Passing Information Using GET Method
GET 方法将编码后的用户信息附加到页面请求后发送。页面和编码后的信息由 ? 字符分隔,如下所示:
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows −
http://www.test.com/cgi-bin/cpp.cgi?key1=value1&key2=value2
GET 方法是将信息从浏览器传递到 Web 服务器的默认方法,它会在浏览器的“位置”框中生成一个长字符串。如果要将密码或其他敏感信息传递给服务器,切勿使用 GET 方法。GET 方法有大小限制,您可以在请求字符串中传递多达 1024 个字符。
The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser’s Location:box. Never use the GET method if you have password or other sensitive information to pass to the server. The GET method has size limitation and you can pass upto 1024 characters in a request string.
在使用 GET 方法时,信息是通过 QUERY_STRING http 头信息传递的,可以通过 QUERY_STRING 环境变量在 CGI 程序中访问。
When using GET method, information is passed using QUERY_STRING http header and will be accessible in your CGI Program through QUERY_STRING environment variable.
您可以简单地将键值对与任何 URL 连接起来传递信息,也可以使用 HTML <FORM> 标记使用 GET 方法传递信息。
You can pass information by simply concatenating key and value pairs alongwith any URL or you can use HTML <FORM> tags to pass information using GET method.
Simple URL Example: Get Method
这是一个简单的 URL,将使用 GET 方法向 hello_get.py 程序传递两个值。
Here is a simple URL which will pass two values to hello_get.py program using GET method.
这是一个生成 cpp_get.cgi CGI 程序来处理 Web 浏览器提供输入的程序。我们要使用 C++ CGI 库,它使得访问传递的信息非常容易 −
Below is a program to generate cpp_get.cgi CGI program to handle input given by web browser. We are going to use C++ CGI library which makes it very easy to access passed information −
#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>Using GET and POST Methods</title>\n";
cout << "</head>\n";
cout << "<body>\n";
form_iterator fi = formData.getElement("first_name");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "First name: " << **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 << "Last name: " << **fi << endl;
} else {
cout << "No text entered for last name" << endl;
}
cout << "<br/>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
现在,如下编译上述程序 −
Now, compile the above program as follows −
$g++ -o cpp_get.cgi cpp_get.cpp -lcgicc
生成 cpp_get.cgi 并将其放在 CGI 目录中,然后尝试使用以下链接进行访问 −
Generate cpp_get.cgi and put it in your CGI directory and try to access using following link −
这将生成以下结果 −
This would generate following result −
First name: ZARA
Last name: ALI
Simple FORM Example: GET Method
这是一个使用 HTML FORM 和提交按钮传递两个值的简单示例。我们要使用相同的 CGI 脚本 cpp_get.cgi 来处理此输入。
Here is a simple example which passes two values using HTML FORM and submit button. We are going to use same CGI script cpp_get.cgi to handle this input.
<form action = "/cgi-bin/cpp_get.cgi" method = "get">
First Name: <input type = "text" name = "first_name"> <br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
这是上述表单的实际输出。您输入名字和姓氏,然后单击提交按钮查看结果。
Here is the actual output of the above form. You enter First and Last Name and then click submit button to see the result.
Passing Information Using POST Method
向 CGI 程序传递信息的一个通常更为可靠的方法是 POST 方法。此方法将信息打包的方式与 GET 方法完全相同,但是不是在 URL 中的 ? 之后作为文本字符串发送信息,而是作为单独的消息发送信息。此消息以标准输入的形式进入 CGI 脚本。
A generally more reliable method of passing information to a CGI program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes into the CGI script in the form of the standard input.
同一个 cpp_get.cgi 程序还将处理 POST 方法。让我们采用与上面相同的示例,它使用 HTML FORM 和提交按钮传递两个值,但这次使用 POST 方法如下 −
The same cpp_get.cgi program will handle POST method as well. Let us take same example as above, which passes two values using HTML FORM and submit button but this time with POST method as follows −
<form action = "/cgi-bin/cpp_get.cgi" method = "post">
First Name: <input type = "text" name = "first_name"><br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
这是上述表单的实际输出。您输入名字和姓氏,然后单击提交按钮查看结果。
Here is the actual output of the above form. You enter First and Last Name and then click submit button to see the result.
Passing Checkbox Data to CGI Program
如果要求选择多个选项,则使用复选框。
Checkboxes are used when more than one option is required to be selected.
这是一个包含两个复选框的表单的示例 HTML 代码−
Here is example HTML code for a form with two checkboxes −
<form action = "/cgi-bin/cpp_checkbox.cgi" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" value = "on" /> Maths
<input type = "checkbox" name = "physics" value = "on" /> Physics
<input type = "submit" value = "Select Subject" />
</form>
这段代码的结果是以下表单−
The result of this code is the following form −
这是一个 C++ 程序,它将生成 cpp_checkbox.cgi 脚本来处理通过复选框按钮从 Web 浏览器提供的输入。
Below is C++ program, which will generate cpp_checkbox.cgi script to handle input given by web browser through checkbox button.
#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;
bool maths_flag, physics_flag;
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Checkbox Data to CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";
maths_flag = formData.queryCheckbox("maths");
if( maths_flag ) {
cout << "Maths Flag: ON " << endl;
} else {
cout << "Maths Flag: OFF " << endl;
}
cout << "<br/>\n";
physics_flag = formData.queryCheckbox("physics");
if( physics_flag ) {
cout << "Physics Flag: ON " << endl;
} else {
cout << "Physics Flag: OFF " << endl;
}
cout << "<br/>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
Passing Radio Button Data to CGI Program
如果要求只选择一个选项,则使用单选按钮。
Radio Buttons are used when only one option is required to be selected.
这是一个带有两个单选按钮的表单的示例 HTML 代码 −
Here is example HTML code for a form with two radio button −
<form action = "/cgi-bin/cpp_radiobutton.cgi" method = "post" target = "_blank">
<input type = "radio" name = "subject" value = "maths" checked = "checked"/> Maths
<input type = "radio" name = "subject" value = "physics" /> Physics
<input type = "submit" value = "Select Subject" />
</form>
这段代码的结果是以下表单−
The result of this code is the following form −
这是一个 C++ 程序,它将生成 cpp_radiobutton.cgi 脚本来处理通过单选按钮从 Web 浏览器提供的输入。
Below is C++ program, which will generate cpp_radiobutton.cgi script to handle input given by web browser through radio buttons.
#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>Radio Button Data to CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";
form_iterator fi = formData.getElement("subject");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "Radio box selected: " << **fi << endl;
}
cout << "<br/>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
Passing Text Area Data to CGI Program
如果必须将多行文本传递给 CGI 程序,则使用 TEXTAREA 元素。
TEXTAREA element is used when multiline text has to be passed to the CGI Program.
这是一个包含一个 TEXTAREA 框的表单的示例 HTML 代码−
Here is example HTML code for a form with a TEXTAREA box −
<form action = "/cgi-bin/cpp_textarea.cgi" method = "post" target = "_blank">
<textarea name = "textcontent" cols = "40" rows = "4">
Type your text here...
</textarea>
<input type = "submit" value = "Submit" />
</form>
这段代码的结果是以下表单−
The result of this code is the following form −
这是一个 C++ 程序,它将生成 cpp_textarea.cgi 脚本来处理通过文本区域从 Web 浏览器提供的输入。
Below is C++ program, which will generate cpp_textarea.cgi script to handle input given by web browser through text area.
#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>Text Area Data to CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";
form_iterator fi = formData.getElement("textcontent");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "Text Content: " << **fi << endl;
} else {
cout << "No text entered" << endl;
}
cout << "<br/>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
Passing Drop down Box Data to CGI Program
当我们有很多选项可用但只选择一个或两个选项时,会使用下拉框。
Drop down Box is used when we have many options available but only one or two will be selected.
这是一个包含一个下拉框的表单的示例 HTML 代码−
Here is example HTML code for a form with one drop down box −
<form action = "/cgi-bin/cpp_dropdown.cgi" method = "post" target = "_blank">
<select name = "dropdown">
<option value = "Maths" selected>Maths</option>
<option value = "Physics">Physics</option>
</select>
<input type = "submit" value = "Submit"/>
</form>
这段代码的结果是以下表单−
The result of this code is the following form −
这是一个 C++ 程序,它将生成 cpp_dropdown.cgi 脚本来处理通过下拉框从 Web 浏览器提供的输入。
Below is C++ program, which will generate cpp_dropdown.cgi script to handle input given by web browser through drop down box.
#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>Drop Down Box Data to CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";
form_iterator fi = formData.getElement("dropdown");
if( !fi->isEmpty() && fi != (*formData).end()) {
cout << "Value Selected: " << **fi << endl;
}
cout << "<br/>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
Using Cookies in CGI
HTTP 协议是一种无状态协议。但是,对于商业网站,需要在不同页面之间维护会话信息。例如,用户注册在完成多个页面后结束。但是,如何在所有 Web 页面中维护用户的会话信息。
HTTP protocol is a stateless protocol. But for a commercial website it is required to maintain session information among different pages. For example one user registration ends after completing many pages. But how to maintain user’s session information across all the web pages.
在许多情况下,使用 cookie 是记忆和跟踪偏好、购买、佣金和其他信息最有效的方法,而这些信息对于提升访问者体验或网站统计至关重要。
In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.
How It Works
您的服务器会以 Cookie 的形式向访客的浏览器发送一些数据。浏览器可能会接受 Cookie。如果接受,它将作为纯文本记录存储在访客硬盘上。现在,当访客到达您站点上的另一个页面时,可以检索 Cookie。检索后,您的服务器知道/记住存储的内容。
Your server sends some data to the visitor’s browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor’s hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored.
Cookie 是纯文本数据记录,包含 5 个可变长度字段:
Cookies are a plain text data record of 5 variable-length fields −
-
Expires − This shows date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
-
Domain − This shows domain name of your site.
-
Path − This shows path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
-
Secure − If this field contains the word "secure" then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
-
Name = Value − Cookies are set and retrieved in the form of key and value pairs.
Setting up Cookies
将 cookie 发送到浏览器非常容易。这些 cookie 将在 Content-type 字段之前随 HTTP 标头一起发送。假设你想将 UserID 和 Password 设置为 cookie。因此,cookie 设置将如下进行:
It is very easy to send cookies to browser. These cookies will be sent along with HTTP Header before the Content-type filed. Assuming you want to set UserID and Password as cookies. So cookies setting will be done as follows
#include <iostream>
using namespace std;
int main () {
cout << "Set-Cookie:UserID = XYZ;\r\n";
cout << "Set-Cookie:Password = XYZ123;\r\n";
cout << "Set-Cookie:Domain = www.tutorialspoint.com;\r\n";
cout << "Set-Cookie:Path = /perl;\n";
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Cookies in CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";
cout << "Setting cookies" << endl;
cout << "<br/>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
从这个示例中,您应该已经了解了如何设置 Cookie。我们使用 Set-Cookie HTTP 标头设置 Cookie。
From this example, you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies.
此处,可以有选择地设置 cookie 属性,如 Expires、Domain 和 Path。值得注意的是,cookie 是在发送魔术行 "Content-type:text/html\r\n\r\n 之前设置的。
Here, it is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending magic line "Content-type:text/html\r\n\r\n.
编译以上程序生成 setcookies.cgi,并尝试使用以下链接设置 cookie。它将在你的电脑上设置四个 cookie -
Compile above program to produce setcookies.cgi, and try to set cookies using following link. It will set four cookies at your computer −
Retrieving Cookies
可以轻松检索所有设置的 cookie。Cookie 存储在 CGI 环境变量 HTTP_COOKIE 中,并且会有以下形式。
It is easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form.
key1 = value1; key2 = value2; key3 = value3....
以下是有关如何检索 cookie 的示例。
Here is an example of how to retrieve cookies.
#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 cgi;
const_cookie_iterator cci;
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>Cookies in CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";
cout << "<table border = \"0\" cellspacing = \"2\">";
// get environment variables
const CgiEnvironment& env = cgi.getEnvironment();
for( cci = env.getCookieList().begin();
cci != env.getCookieList().end();
++cci ) {
cout << "<tr><td>" << cci->getName() << "</td><td>";
cout << cci->getValue();
cout << "</td></tr>\n";
}
cout << "</table><\n";
cout << "<br/>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
现在,编译以上程序生成 getcookies.cgi,并尝试获取电脑上所有可用 cookie 的列表 -
Now, compile above program to produce getcookies.cgi, and try to get a list of all the cookies available at your computer −
这会生成之前部分中设置的所有四个 cookie,以及电脑中设置的所有其他 cookie 的列表 -
This will produce a list of all the four cookies set in previous section and all other cookies set in your computer −
UserID XYZ
Password XYZ123
Domain www.tutorialspoint.com
Path /perl
File Upload Example
要上传文件,HTML 表单必须将 enctype 属性设置为 multipart/form-data 。文件类型为的输入标记将创建一个“浏览”按钮。
To upload a file the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type will create a "Browse" button.
<html>
<body>
<form enctype = "multipart/form-data" action = "/cgi-bin/cpp_uploadfile.cgi"
method = "post">
<p>File: <input type = "file" name = "userfile" /></p>
<p><input type = "submit" value = "Upload" /></p>
</form>
</body>
</html>
这段代码的结果是以下表单−
The result of this code is the following form −
Note - 上面的示例已被有意禁用,以阻止人们在我们服务器上上传文件。但你可以用自己的服务器尝试上面的代码。
Note − Above example has been disabled intentionally to stop people uploading files on our server. But you can try above code with your server.
以下是处理文件上传的脚本 cpp_uploadfile.cpp -
Here is the script cpp_uploadfile.cpp to handle file upload −
#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 cgi;
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>File Upload in CGI</title>\n";
cout << "</head>\n";
cout << "<body>\n";
// get list of files to be uploaded
const_file_iterator file = cgi.getFile("userfile");
if(file != cgi.getFiles().end()) {
// send data type at cout.
cout << HTTPContentHeader(file->getDataType());
// write content at cout.
file->writeToStream(cout);
}
cout << "<File uploaded successfully>\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
上面的示例用于写入 cout 流中的内容,但是你可以打开文件流并将已上传文件的内容保存在所需位置的文件中。
The above example is for writing content at cout stream but you can open your file stream and save the content of uploaded file in a file at desired location.
希望你享受本教程。如果是,请将你的反馈发送给我们。
Hope you have enjoyed this tutorial. If yes, please send us your feedback.