English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Ruby CGI Programming

Ruby is a general-purpose language, not just a language applied to WEB development, but Ruby is most commonly used in the development of WEB applications and WEB tools.

Using Ruby, you can not only write your own SMTP server, FTP program, or Ruby web server, but you can also use Ruby for CGI programming.

Next, let's take some time to learn about Ruby CGI editing.

Web browsing

To better understand how CGI works, we can follow the process of clicking a link or URL on a webpage:

  • 1Use your browser to access the URL and connect to the HTTP web server.

  • 2The web server parses the URL after receiving the request information and checks if the file accessed is present on the server. If it exists, it returns the content of the file; otherwise, it returns an error message.

  • 3The browser receives information from the server and displays the received file or error message.

CGI programs can be Ruby scripts, Python scripts, PERL scripts, SHELL scripts, C or C++ and more.

CGI architecture diagram

Web server support and configuration

Before you start CGI programming, make sure your web server supports CGI and that the CGI handler has been configured.

Apache supports CGI configuration:

Set up the CGI directory:

ScriptAlias /cgi-bin/ /var/www/cgi-bin/

All HTTP servers execute CGI programs and are stored in a pre-configured directory. This directory is called the CGI directory, and by convention, it is named/var/www/cgi-bin directory.

The extension of CGI files is .cgi, and Ruby can also use the .rb extension.

By default, the Linux server configuration runs cgi-The bin directory contains/var/www.

If you want to specify a directory other than the one where CGI scripts run, you can modify the httpd.conf configuration file as follows:

<Directory "/var/www/cgi-bin">
   AllowOverride None
   Options +ExecCGI
   Order allow,deny
   Allow from all
>/Directory>

Add the .rb suffix in AddHandler so that we can access Ruby script files ending with .rb:

AddHandler cgi-script.cgi .pl .rb

Write a CGI script

The most basic Ruby CGI code is as follows:

#!/usr/bin/ruby
puts "Content"-type: text/html\n\n"
puts "<html><body>This is a test</body></html>"

You can keep the code in the test.cgi file, upload it to the server, and grant sufficient permissions to execute it as a CGI script.

If the address of your site is http://www.example.com/ , you can access it via http://www.example.com/Accessing the program with test.cgi, the output is: "This is a test.".

After the browser accesses the URL, the web server will find the test.cgi file in the site directory, then parse the script code with the Ruby parser and access the HTML document.

Using cgi.rb

Ruby can call the CGI library to write more complex CGI scripts.

The following code calls the CGI library to create a CGI script.

#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
puts cgi.header
puts "<html><body>This is a test</body></html>"

In the following code, a CGI object is created and the header information is printed.

Form Processing

The CGI library can be used to obtain data from form submissions (or parameters in URLs) in two ways: For example, URL:/cgi-bin/test.cgi?FirstName=Zara&LastName=Ali。

You can use CGI#[] directly to obtain parameters FirstName and LastName:

#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
cgi['FirstName'] # => ["Zara"]
cgi['LastName'] # => ["Ali"]

Another way to get form data is:

#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
h = cgi.params # => {"FirstName"=>["Zara"], "LastName"=>["Ali"]}
h['FirstName'] # => ["Zara"]
h['LastName'] # => ["Ali"]

The following code is used to retrieve all keys:

#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
cgi.keys # => ["FirstName", "LastName"]

If the form contains multiple fields with the same name, the values of the same field will be stored in an array.

In the following example, three fields with the same name "name" in the form are specified, with values of "Zara", "Huma", and "Nuha":

#!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
cgi['name'] # => "Zara"
cgi.params['name'] # => ["Zara", "Huma", "Nuha"]
cgi.keys # => ["name"]
cgi.params # => {"name"=>["Zara", "Huma", "Nuha"]}

Note:Ruby automatically determines GET and POST methods, so there is no need to treat the two methods differently.

The following is the relevant HTML code:

<html>
<body>
<form method="POST" action="http://www.example.com/test.cgi">
First Name :<input type="text" name="FirstName" value="" />
<br />
Last Name :<input type="text" name="LastName" value="" /> 
<input type="submit" value="Submit Data" />
>/form>
>/body>
>/<

html>

Creating Form Forms and HTML The CGI package includes a large number of methods to create HTML, with each HTML tag having a corresponding method.

Before using these methods, it is necessary to create a CGI object using CGI.new.

#!/usr/bin/ruby
To make the nesting of tags simpler, these methods treat the content as code blocks, which return strings as the content of the tags. As shown below:
require "cgi"4cgi = CGI.new("html
})
   cgi.html{
      cgi.head{ "\n"+cgi.title{"This Is a Test"} } +
      cgi.body{ "\n"+
         cgi.form{"\n"+
            cgi.hr +
            cgi.h1 { "A Form: " } + "\n"+
            cgi.textarea("get_text") +"\n"+
            cgi.br +
            cgi.submit
         }
      }
   }
}

String Escaping

When processing parameters in URLs or HTML form data, it is necessary to escape specified special characters, such as: quotes (") and backslashes (\)/)。

Ruby CGI object provides the CGI.escape and CGI.unescape methods to handle the escaping of these special characters:

#!/usr/bin/ruby
require 'cgi'
puts CGI.escape(Zara Ali/A Sweet & Sour Girl)

The execution result of the above code is as follows:

#!/usr/bin/ruby
require 'cgi'
puts CGI.escape(Zara Ali/A Sweet & Sour Girl)

Another example group:

#!/usr/bin/ruby
require 'cgi'
puts CGI.escapeHTML('<h1>Zara Ali/A Sweet & Sour Girl</h1>')

The execution result of the above code is as follows:

<h1>Zara Ali/A Sweet & Sour Girl</h1'>

Common Methods in CGI Class

The following are the complete methods related to the CGI class in Ruby

  • Ruby CGI  - Standard CGI Library Related Methods

Cookies and Sessions