You get a bonus - 1 coin for daily activity. Now you have 1 coin

Purpose of the CGI interface. CGI applications

Lecture



At the dawn of the Internet, developers needed to find a way to run scripts on the server to generate page content and use other processes. For this, a Common Gateway Interface (CGI) protocol was developed.

CGI determines the environment (environment variables, query for specific variables, etc.), how the script will be executed and how data is transferred between the script and the web server. For each request, CGI sets up the environment, spawns a running instance of the script and sends all the data it contains, and also captures and sends the output of the script to the server.

  Purpose of the CGI interface.  CGI applications

The term CGI (Common Gateway Interface) refers to the set of agreements that Web servers must adhere to when they run various Web applications. In fact, until recently, all Web programming was programming CGI applications. Recently the situation has changed. Started using FastCGI or other protocols methods and interfaces. And although CGI is still the unspoken standard for Web applications, the mechanism of the CGI programs has been somewhat updated.

Suppose you type http://www.server.com/path/pict.gif in your browser

After the http request you entered, the server sends you the requested GIF image (of course, if it is available at the specified address). However, it is impossible to say that you requested exactly the picture. Why? The fact is that the pict.gif file may not be a picture or even exist at all. Surprised? And this is nothing but a manifestation of CGI. First, the pict.gif file and the path / path / may not exist, because the web server administrator can set up aliases (aliases) for this object on the server. Secondly, the pict.gif file can generate a CGI program on the fly, transferring the finished GIF image to the browser. Exactly in this case CGI tools were used. This mechanism is completely invisible to the user of the resource, who does not care how the picture appeared in his browser - the browser transferred the file or the file was transferred by the program. Similarly, you can send html-documents, in which case they can be generated by the program dynamically and transmitted to users' browsers in response to their requests.

The last point is particularly impressive. If you are inspired by his idea, it means that you have understood in general terms what a CGI is. Just CGI provides everything that looks so transparent to the user. Traditionally, programs that operate under CGI conventions are called scripts — most likely due to the fact that in most cases they are written in interpreter languages ​​(for example, in PHP or Perl).

Thus, we can use a powerful mechanism that allows us to generate documents on the fly.

For example, we need a current date and time to appear in a document. Of course, we cannot pre-register them in the document - after all, depending on when it is loaded by the user, this date should change. But we can write a script (script) that will calculate the date, insert it into the document and then transfer it to the user! However, in the model we have built, one link is missing. Indeed, suppose we need the time in our page to be stamped based on the user's time zone. But how does the script know what time zone is the region in which this person lives (or any other information that the user can provide)? Apparently, there must be some kind of mechanism that will allow the user not only to receive, but also pass on information to the server (in this case, for example, the time correction in hours relative to Moscow). This also provides CGI.

Server interaction with the browser

What happens when we enter a URL into the address bar of the browser? The browser extracts the protocol (http) and the web server address from the URL. Next, the browser accesses the server with an HTTP request, which indicates that it is necessary to receive the document / path /somefile.html . The server views the contents of the directory, and if it finds the document somefile.html , it returns it to the browser in plain text. In addition to text, the server also returns the document type (format). For example, if the web server reports that the file somefile.html is text, then we will see the HTML code in the browser window. But usually the server tells the browser that somefile.html is a hypertext document (html), so we will see a normal html page. If the document requested by the browser is not found, the server will send us an error message.

Purpose of the CGI Interface

The CGI interface acts as a gateway between the various programs installed on the web server and user browsers. When a browser requests a specific resource, the web server launches a program that already returns the result to the user's browser. The use of CGI programs is required when it is necessary to display a page in the user's browser that is based on any user actions. For example, you entered into the form any data, and on the basis of them the page sent to you is formed. The CGI program can also determine the IP address of your computer on the network and, based on it, determine your country, eventually giving you the html document in your own language!

The CGI mechanism redirects the output of the program to the web server, and that, in turn, to the user's browser. From the point of view of the program, there is nothing unusual - it only displays information. Absolutely any program cannot be a CGI-program, because before its output it must output certain server headers — specify at least the type of information output. For example, if we want to display a picture, we must send the header Content-type: image / gif. If the CGI program needs to pass parameters, then this is done very simply - as is the case with a regular program. For example, we need to pass the query string name=Ivan&email=ivan@ivanov.com to the cgi.exe script. To do this, call the cgi.exe program with the specified query string: cgi.exe name=Ivan&email=ivan@ivanov.com .

Separate parameters with an &. Have you ever seen on the page several input fields and switches, and below them the "Send" button? This is the form with its help
You can automate the process of transferring data to the script. Of course, the script must again adequately respond to these parameters: to parse the string, create variables, etc. It should be noted that all these actions will have to be programmed manually if we want to use the C language. PHP parses the query string parameters yourself.

So, this method of sending parameters to the script (when data is placed on the URL command line) is called the GET method. In fact, even if no parameters are passed (for example, when loading a static page), the GET method is still used. However, there is another common method - transferring request parameters using the POST method. We will look at the methods for submitting requests below.

If the program is designed for CGI, then you need to take care of the interaction with the server. The simplest interaction is that the programmer needs to know the server information. This information is transmitted using environment variables.

This is how the CGI mechanism works.

Ways to create CGI scripts (scripts)

CGI programs are often written in some interpretable language (PHP, Perl, Bash, Phyton, etc.). You can also write a program in a compiled language, such as C , which will process user data. Here is an example of a CGI program in C:

#include <time.h> // Нужна для инициализации функции rand()
#include <stdio.h> // Включаем поддержку функций ввода/вывода
#include <stdlib.h> // А это — для поддержки функции rand()
// Главная функция. Именно она и запускается при старте сценария.
void main(void) {
// инициализируем генератор случайных чисел
int Num; time_t t; srand(time(&t));
// в Num записывается случайное число от 0 до 9
Num = rand()%10;
// далее выводим заголовки ответа. Тип — html-документ
printf("Content-type: text/html\n");
// запрет кэширования
printf("Pragma: no-cache\n");
// пустой заголовок
printf("\n");
// выводим текст документа — его мы увидим в браузере
printf("<html><body>");
printf("<h1>Здравствуйте!</h1>");
printf("Случайное число в диапазоне 0-9: %d",Num);
printf("</body></html>");
}

Now we can compile this program into the executable (binary) file cgi.exe and access it as a CGI script.

Currently using a modernized interface FastCGI

Next, we finally consider the methods for sending requests.


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)