Easy Tutorial
❮ Ruby Cgi Methods Ruby Decision ❯

Ruby CGI Programming

Ruby is a versatile language, not just limited to web development, but it is most commonly used in web applications and web tools.

With 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's CGI scripting.


Web Browsing

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

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


CGI Architecture Diagram


Web Server Support and Configuration

Before you start CGI programming, ensure that your web server supports CGI and has been configured to handle CGI scripts.

Apache supports CGI configuration:

Set up the CGI directory:

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

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

CGI files have the extension .cgi, and Ruby can also use the .rb extension.

By default, Linux servers configure the cgi-bin directory to run at /var/www.

If you want to specify a different directory for running CGI scripts, 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

Writing CGI Scripts

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 save this code to a file named test.cgi, upload it to the server, and give it sufficient permissions to be executed as a CGI script.

If your site's address is http://www.example.com/, you can access this program via http://www.example.com/test.cgi, and the output will be: "This is a test."

When the browser accesses this URL, the web server will find the test.cgi file in the site directory, then parse the script code with the Ruby interpreter, 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 Handling

The CGI library can retrieve form data (or parameters in the URL) in two ways.

For example, the URL: /cgi-bin/test.cgi?FirstName=Zara&LastName=Ali.

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

#!/usr/bin/ruby

require 'cgi'
cgi = CGI.new
cgi['FirstName'] # => ["Zara"]
cgi['LastName']  # => ["Ali"]

Another way to get form data:

#!/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 these fields will be stored in an array.

In the following example, three fields with the name "name" are specified in the form, with values "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 distinguishes between GET and POST methods, so there is no need to treat them differently.

The following is the related 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 and HTML

CGI includes a large number of methods for creating HTML. Each HTML tag has a corresponding method.

Before using these methods, you must create a CGI object with CGI.new.

To make tag nesting easier, these methods take the content as a block, which returns a string as the content of the tag. For example:

#!/usr/bin/ruby

require "cgi"
cgi = CGI.new("html4")
cgi.out{
   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 dealing with parameters in URLs or HTML form data, you need to escape certain special characters, such as quotes (") and backslashes (/).

The 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 above code outputs the following:

Zara+Ali%2FA+Sweet+%26+Sour+Girl

Another example:

#!/usr/bin/ruby

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

The above code outputs the following:

&lt;h1&gt;Zara Ali/A Sweet & Sour Girl&lt;/h1&gt;

Common Methods in the CGI Class

Here are the complete methods of the CGI class in Ruby:

-Ruby CGI - Standard CGI library methods


Cookies and Sessions

-Ruby CGI Cookies - How to handle CGI cookies.

-Ruby CGI Sessions - How to handle CGI sessions.

❮ Ruby Cgi Methods Ruby Decision ❯