The best C ++ Web Programming Tutorial In 2024, In this tutorial you can learn What is CGI?,Web Browser,CGI Chart,Web server configuration,The first CGI program,Hello World! This is my first CGI program,HTTP header information,CGI Environment Variables,C ++ CGI library,GET and POST methods,Use the GET method to pass information,Simple URL Examples: Get Method,Examples of simple form: GET method,Using the POST method to transmit information,CGI program to pass data to the box,Transfer data to the CGI program the radio button,Transfer data to a CGI program text area,Drop-down box to pass data to the CGI program,Use Cookies in CGI,,Examples of file uploads,
To better understand the concept of CGI, let's click on a hyperlink, browse a specific page or URL, and see what happens.
However, in such a way to build up an HTTP server, regardless of when to request a file directory, the HTTP server is not sending back the file, but in the form of program execution and the implementation of the output generated is sent back to the browser display come out.
Common Gateway Interface (CGI), is to make an application (called CGI programs or CGI scripts) to work with Web servers and clients interact standard protocols. These CGI programs can use Python, PERL, Shell, C or C ++, etc. to prepare.
The following illustration shows the CGI architecture:
Before you make CGI programming, make sure that your Web server supports CGI, and has been configured to handle CGI programs. All CGI programs executed by the HTTP server, have to be pre-configured directory. This directory called CGI directory, by convention named / var / www / cgi-bin. Although CGI executable file is C ++, but by convention, it is the extension.cgi.
By default, Apache Web server would be configured to run in the / var / www / cgi-bin in the CGI program. If you want to specify another directory to run CGI scripts, you can modify the following section in 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>
Here, we are assuming you already have a Web server and can be run successfully, you can run any CGI programs, such as Perl or Shell and the like.
Consider the following C ++ program:
#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 - 第一个 CGI 程序</title>\n"; cout << "</head>\n"; cout << "<body>\n"; cout << "<h2>Hello World! 这是我的第一个 CGI 程序</h2>\n"; cout << "</body>\n"; cout << "</html>\n"; return 0; }
Compile the previous code, the executable file is named cplusplus.cgi, and this file is saved in / var / www / cgi-bin directory. Before running the CGI program, please use thechmod 755 cplusplus.cgi UNIX command to change the file mode, make sure the file is executable.Access executable file, you will see the following output:
The above C ++ program is a simple program, it's written on STDOUT output file is displayed on the screen. Here, it is noteworthy that the first line of outputContent-type: text / html \ r \ n \ r \ n.This line is sent back to the browser, and destined to be displayed in the browser window content type. You must understand the basic concepts of CGI, so as to further use Python to write more complex CGI program. C ++ CGI program can be used with any other external systems (such as RDBMS) to interact.
LineContent-type: text / html \ r \ n \ r \ n is an integral part of the HTTP header information, it is sent to the browser, in order to better understand the content of the page.In the form of HTTP header information is as follows:
HTTP 字段名称: 字段内容 例如 Content-type: text/html\r\n\r\n
There are other important HTTP header information, these will often be used in your CGI programming.
头信息 | 描述 |
---|---|
Content-type: | MIME 字符串,定义返回的文件格式。例如 Content-type:text/html。 |
Expires: Date | 信息变成无效的日期。浏览器使用它来判断一个页面何时需要刷新。一个有效的日期字符串的格式应为 01 Jan 1998 12:00:00 GMT。 |
Location: URL | 这个 URL 是指应该返回的 URL,而不是请求的 URL。你可以使用它来重定向一个请求到任意的文件。 |
Last-modified: Date | 资源的最后修改日期。 |
Content-length: N | 要返回的数据的长度,以字节为单位。浏览器使用这个值来表示一个文件的预计下载时间。 |
Set-Cookie: String | 通过string设置 cookie。 |
All CGI programs can access the following environment variables. These variables when writing CGI programs play a very important role.
变量名 | 描述 |
---|---|
CONTENT_TYPE | 内容的数据类型。当客户端向服务器发送附加内容时使用。例如,文件上传等功能。 |
CONTENT_LENGTH | 查询的信息长度。只对 POST 请求可用。 |
HTTP_COOKIE | 以键 & 值对的形式返回设置的 cookies。 |
HTTP_USER_AGENT | 用户代理请求标头字段,递交用户发起请求的有关信息,包含了浏览器的名称、版本和其他平台性的附加信息。 |
PATH_INFO | CGI 脚本的路径。 |
QUERY_STRING | 通过 GET 方法发送请求时的 URL 编码信息,包含 URL 中问号后面的参数。 |
REMOTE_ADDR | 发出请求的远程主机的 IP 地址。这在日志记录和认证时是非常有用的。 |
REMOTE_HOST | 发出请求的主机的完全限定名称。如果此信息不可用,则可以用 REMOTE_ADDR 来获取 IP 地址。 |
REQUEST_METHOD | 用于发出请求的方法。最常见的方法是 GET 和 POST。 |
SCRIPT_FILENAME | CGI 脚本的完整路径。 |
SCRIPT_NAME | CGI 脚本的名称。 |
SERVER_NAME | 服务器的主机名或 IP 地址。 |
SERVER_SOFTWARE | 服务器上运行的软件的名称和版本。 |
The following lists all CGI programs 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 环境变量</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>"; // 尝试检索环境变量的值 char *value = getenv( ENV[ i ].c_str() ); if ( value != 0 ){ cout << value; }else{ cout << "环境变量不存在。"; } cout << "</td></tr>\n"; } cout << "</table><\n"; cout << "</body>\n"; cout << "</html>\n"; return 0; }
In a real example, you need to perform many operations by CGI programs. There is a program designed specifically for C ++ written CGI library, we can ftp://ftp.gnu.org/gnu/cgicc/ download this CGI library, the library and installed in accordance with the following steps:
$tar xzf cgicc-X.X.X.tar.gz $cd cgicc-X.X.X/ $./configure --prefix=/usr $make $make install
You can click on the C ++ the CGI Lib the Documentation , view library documents.
You may have encountered such a situation, when you need to pass some information from the browser to the Web server, and finally passed to the CGI program. Typically browsers are two ways to use this information to the Web server are GET and POST methods.
GET method to send the user information encoded appended to the page request. Pages and encoded information separated by character, as follows?:
http://www.test.com/cgi-bin/cpp.cgi?key1=value1&key2=value2
GET method is the default method from the browser to the Web server information transfer, it is a long string of string is generated in the browser's address bar. When a password or other sensitive information that you pass to the server, do not use the GET method. GET method is limited in size, in a transfer request string up to 1024 characters.
When you use the GET method is to use the QUERY_STRING http header to transmit information, use the QUERY_STRING environment variable in CGI programs to access.
You can keep up with the key in the URL of simple connection, you can also use HTML GET method <FORM> tag to transmit information.
Here is a simple URL, using GET method to pass two values to hello_get.py program.
/cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI
The following examples generatecpp_get.cgi CGI program for processing the input given by the Web browser.By using the C ++ CGI library, you can easily access information transmission:
#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; }
Now, compile the above program as follows:
$g++ -o cpp_get.cgi cpp_get.cpp -lcgicc
Generate cpp_get.cgi, and put it in the CGI directory and try to access the following link:
/cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI
This produces the following results:
名:ZARA 姓:ALI
Here is a simple example, using HTML forms and submit button passes the two values. We will use the same CGI script cpp_get.cgi to process the input.
<form action="/cgi-bin/cpp_get.cgi" method="get"> 名:<input type="text" name="first_name"> <br /> 姓:<input type="text" name="last_name" /> <input type="submit" value="提交" /> </form>
Here is the actual output of the form, enter the first and last name, then click on the submit button to view the results.
A more reliable method of passing information to the CGI program is POST method. This method of packaging information with the GET method the same way, except that it is not the message as a text string in the URL? After be passed, but put it in a separate message in the form of delivery. The message is passed to the standard input in the form of CGI scripts.
We also use cpp_get.cgi to handle POST method. Let's take the same example, to pass through the use of HTML forms and submit button two values, but this time we are not using the GET method, but the POST method, as follows:
<form action="/cgi-bin/cpp_get.cgi" method="post"> 名:<input type="text" name="first_name"><br /> 姓:<input type="text" name="last_name" /> <input type="submit" value="提交" /> </form>
When you need to select multiple options, we are using the checkboxes.
The following HTML code example is a form with two checkboxes:
<form action="/cgi-bin/cpp_checkbox.cgi" method="POST" target="_blank"> <input type="checkbox" name="maths" value="on" /> 数学 <input type="checkbox" name="physics" value="on" /> 物理 <input type="submit" value="选择学科" /> </form>
The following C ++ program will generate cpp_checkbox.cgi script to handle Web browser by entering the box given.
#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>向 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; }
When only need to select an option, we use radio buttons.
The following HTML code example is a form with two radio buttons:
<form action="/cgi-bin/cpp_radiobutton.cgi" method="post" target="_blank"> <input type="radio" name="subject" value="maths" checked="checked"/> 数学 <input type="radio" name="subject" value="physics" /> 物理 <input type="submit" value="选择学科" /> </form>
The following C ++ program will generate cpp_radiobutton.cgi script to handle the input Web browser via the radio button of.
#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>向 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; }
CGI program when you need to transfer multiple lines of text, we use the TEXTAREA element.
The following HTML code example is a form with TEXTAREA box:
<form action="/cgi-bin/cpp_textarea.cgi" method="post" target="_blank"> <textarea name="textcontent" cols="40" rows="4"> 请在这里输入文本/en. </textarea> <input type="submit" value="提交" /> </form>
The following C ++ program will generate cpp_textarea.cgi script to handle the input given by the Web browser, the 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>向 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; }
When there are multiple options available, but can only choose one or two options, we use the drop-down box.
The following HTML code example is a form with a drop-down box:
<form action="/cgi-bin/cpp_dropdown.cgi" method="post" target="_blank"> <select name="dropdown"> <option value="Maths" selected>数学</option> <option value="Physics">物理</option> </select> <input type="submit" value="提交"/> </form>
The following C ++ program will generate cpp_dropdown.cgi script to handle the input Web browser via drop-down box given.
#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>向 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; }
HTTP protocol is a stateless protocol. But for a business website, it needs to keep session information between different pages. For example, a user after the completion of multiple steps end registration page. However, how to maintain the user's session info on every page.
In many cases, the use of cookies is to remember and track information regarding user preferences, purchase, commission and other most effective method for the pursuit of a better visitor experience or site statistics required information.
Server in the form of a cookie to send some data to the visitor's browser. If the browser accepts the cookie, the cookie will be stored as plain text recorded on a visitor's hard drive. Now, when visitors to another page on the site, retrieves the cookie. Once you find the cookie, the server will know what is stored.
A cookie is a pure text data records, five variable-length fields with:
Send cookies to the browser is very simple. These cookies will be before the Content-type field, and HTTP headers to be sent together. Suppose you want to set UserID and Password for the cookies, set cookies steps are 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.w3cschool.cc;\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>CGI 中的 Cookies</title>\n"; cout << "</head>\n"; cout << "<body>\n"; cout << "设置 cookies" << endl; cout << "<br/>\n"; cout << "</body>\n"; cout << "</html>\n"; return 0; }
From this example, we learned how to set cookies. We use theSet-Cookie HTTP header to set cookies.
Here are some properties to set cookies is optional, such as Expires, Domain and Path. It is worth noting, cookies are sent in the line"Content-type: text / html \ r \ n \ r \ nbefore being set.
Compile the above program that generates setcookies.cgi, and try to use the following link to set cookies. It will set up four cookies on your computer:
/cgi-bin/setcookies.cgi
cookies to retrieve all the settings are very simple. cookies are stored in the CGI environment variables HTTP_COOKIE, and their form is stored as follows:
key1=value1;key2=value2;key3=value3/en/en
The following example shows how to get 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>CGI 中的 Cookies</title>\n"; cout << "</head>\n"; cout << "<body>\n"; cout << "<table border = \"0\" cellspacing = \"2\">"; // 获取环境变量 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; }
Now, compile the above program generates getcookies.cgi, and try to use the following link to get all the available cookies on your computer:
/cgi-bin/getcookies.cgi
This will produce a list that shows all the other four cookies cookies on a set and your computer:
UserID XYZ Password XYZ123 Domain www.w3cschool.cc Path /perl
To upload a file, HTML form must enctype attribute set tomultipart / form-data.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>文件:<input type="file" name="userfile" /></p> <p><input type="submit" value="上传" /></p> </form> </body> </html>
The results of this code is the following form:
Note: The above example has been deliberately disabled in saved on our servers to upload files.You can try the above code on your server.
The following are used to process the file upload scriptcpp_uploadfile.cpp:
#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>CGI 中的文件上传</title>\n"; cout << "</head>\n"; cout << "<body>\n"; // 获取要被上传的文件列表 const_file_iterator file = cgi.getFile("userfile"); if(file != cgi.getFiles().end()) { // 在 cout 中发送数据类型 cout << HTTPContentHeader(file->getDataType()); // 在 cout 中写入内容 file->writeToStream(cout); } cout << "<文件上传成功>\n"; cout << "</body>\n"; cout << "</html>\n"; return 0; }
The above example is to write tocout stream, but you can open the file stream, and the contents of the uploaded file in a file on the target location.