How to Use Perl for Web Development with CGI
Perl, a powerful and versatile programming language, has been a go-to tool for developers since its creation in the late 1980s.
Although newer languages like Python and Ruby have gained popularity, Perl remains relevant for web development, particularly in legacy systems and server-side scripting.
One of Perl’s primary uses in web development is through the Common Gateway Interface (CGI), a protocol that facilitates the interaction between web servers and programs.
This comprehensive guide will delve into how Perl can be used for web development with CGI. We’ll discuss its strengths, practical applications, and key techniques, along with detailed examples to provide hands-on experience.
🍓For non-member: read full article
1. Introduction to Perl and CGI
What is Perl?
Perl is a high-level, general-purpose programming language designed for text processing, but its versatility allows it to perform tasks like system administration, web development, and network programming.
- Perl’s flexibility, extensive libraries (CPAN), and robust regular expression capabilities make it an excellent choice for web developers.
What is CGI?
The Common Gateway Interface (CGI) is a standard protocol used to interface external programs with web servers.
- It enables web servers to execute external programs and pass their output back to clients via HTTP.
- CGI scripts can be written in various languages, but Perl is one of the most commonly used due to its simplicity and powerful string manipulation capabilities.
2. Setting Up Your Environment
Prerequisites
- A basic understanding of Perl programming.
- A web server capable of handling CGI scripts (e.g., Apache).
- Perl installed on your machine (verify by running
perl -v
).
Configuring the Web Server
For this tutorial, we’ll use Apache:
- Install Apache:
Use your package manager to install Apache. For instance, on Debian-based systems:
sudo apt-get update
sudo apt-get install apache2
2. Enable CGI Module:
Enable CGI in Apache by running:
sudo a2enmod cgi
sudo systemctl restart apache2
3. Set Up the CGI Directory:
Ensure the cgi-bin
directory is enabled. Typically, this is located at /usr/lib/cgi-bin
or a directory specified in your Apache configuration.
You can define a custom CGI directory by adding the following to your Apache configuration:
<Directory "/var/www/html/cgi-bin">
Options +ExecCGI
AddHandler cgi-script .cgi .pl
</Directory>
4. Test the Configuration:
Create a simple test script:
#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "Hello, World!";
Save this as test.cgi
in your cgi-bin
directory, give it execution permissions:
chmod +x /var/www/html/cgi-bin/test.cgi
Navigate to http://your-server-ip/cgi-bin/test.cgi
to ensure it works.
3. Writing Your First Perl CGI Script
Let’s start with a simple script that takes user input and responds dynamically.
HTML Form to Capture Input
Create an HTML file (form.html
) with the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Perl CGI Form</title>
</head>
<body>
<h1>Enter Your Name</h1>
<form action="/cgi-bin/hello.pl" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Submit</button>
</form>
</body>
</html>
Perl Script to Handle Input
Save the following code as hello.pl
in your CGI directory:
#!/usr/bin/perl
use strict;
use warnings;
use CGI;
# Create CGI object
my $cgi = CGI->new;
# Get the input
my $name = $cgi->param('name');
# Output response
print $cgi->header('text/html');
print "<html><body>";
print "<h1>Hello, $name!</h1>";
print "</body></html>";
Explanation:
use CGI
: Loads the CGI module, which simplifies handling HTTP requests and responses.$cgi->param
: Retrieves user input sent through the form.$cgi->header
: Sends an HTTP header specifying the content type astext/html
.- The script dynamically generates an HTML page displaying the user’s input.
4. Adding Advanced Features
4.1. Handling Multiple Parameters
Modify the HTML form to include more fields:
<form action="/cgi-bin/user_info.pl" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<button type="submit">Submit</button>
</form>
Update the Perl script (user_info.pl
):
#!/usr/bin/perl
use strict;
use warnings;
use CGI;
my $cgi = CGI->new;
# Retrieve input parameters
my $name = $cgi->param('name');
my $email = $cgi->param('email');
# Generate response
print $cgi->header('text/html');
print "<html><body>";
print "<h1>User Information</h1>";
print "<p>Name: $name</p>";
print "<p>Email: $email</p>";
print "</body></html>";
4.2. Validating User Input
Use Perl’s built-in functions for validation:
if ($name =~ /\W/ || $email !~ /^[\w\.\-]+@[\w\-]+\.\w+$/) {
print $cgi->header('text/html');
print "<html><body>";
print "<h1>Error: Invalid input</h1>";
print "</body></html>";
exit;
}
4.3. Writing to a File
Store user information in a text file:
open(my $fh, '>>', 'user_data.txt') or die "Cannot open file: $!";
print $fh "Name: $name, Email: $email\n";
close $fh;
5. Creating a Dynamic Application
Scenario: Feedback Form with Database Integration
Enhance functionality by connecting to a database to store and retrieve feedback.
Setting Up the Database
Use SQLite for simplicity:
sudo apt-get install sqlite3
sqlite3 feedback.db "CREATE TABLE feedback (id INTEGER PRIMARY KEY, name TEXT, email TEXT, comments TEXT);"
Perl Script for Handling Feedback
#!/usr/bin/perl
use strict;
use warnings;
use CGI;
use DBI;
my $cgi = CGI->new;
# Retrieve form data
my $name = $cgi->param('name');
my $email = $cgi->param('email');
my $comments = $cgi->param('comments');
# Connect to SQLite database
my $dbh = DBI->connect("dbi:SQLite:dbname=feedback.db", "", "", { RaiseError => 1 }) or die $DBI::errstr;
# Insert feedback into database
my $sth = $dbh->prepare("INSERT INTO feedback (name, email, comments) VALUES (?, ?, ?)");
$sth->execute($name, $email, $comments);
# Generate response
print $cgi->header('text/html');
print "<html><body>";
print "<h1>Thank You!</h1>";
print "<p>Your feedback has been recorded.</p>";
print "</body></html>";
$sth->finish;
$dbh->disconnect;
Reading Feedback
To display all feedback, create another script:
#!/usr/bin/perl
use strict;
use warnings;
use CGI;
use DBI;
my $cgi = CGI->new;
print $cgi->header('text/html');
my $dbh = DBI->connect("dbi:SQLite:dbname=feedback.db", "", "", { RaiseError => 1 }) or die $DBI::errstr;
my $sth = $dbh->prepare("SELECT name, email, comments FROM feedback");
$sth->execute();
print "<html><body><h1>Feedback</h1><ul>";
while (my @row = $sth->fetchrow_array) {
print "<li><strong>$row[0]</strong> ($row[1]): $row[2]</li>";
}
print "</ul></body></html>";
$sth->finish;
$dbh->disconnect;
6. Security Best Practices
- Sanitize Inputs: Use regular expressions to validate inputs and prevent injection attacks.
- Escape Output: Use
HTML::Entities
to encode output before displaying it in HTML. - Use HTTPS: Secure communication with SSL/TLS.
- Restrict File Permissions: Ensure scripts and directories have appropriate permissions.
🌈 Conclusion
Perl, combined with CGI, offers a straightforward yet powerful way to develop dynamic web applications.
While CGI might be less commonly used in modern frameworks, it remains a practical solution for legacy systems and lightweight tasks.
With features like robust text processing, extensive libraries, and seamless integration with databases, Perl continues to be a reliable choice for web development.
This tutorial covered setting up a development environment, writing CGI scripts, handling user inputs, validating and storing data, and integrating with a database. Armed with these skills, you can build and deploy effective web applications with Perl and CGI.
🐦🔥 More Interesting Topics on Perl



Thank you for reading. Before you go 🙋♂️:
Please clap for the writer ️️️
🏌️♂️ Follow me: https://medium.com/@mayurkoshti12
🤹 Follow Publication: https://medium.com/the-code-compass