The Wayback Machine - https://web.archive.org/web/20241004052629/https://www.geeksforgeeks.org/how-to-handle-form-data-in-cgi-scripts/
Open In App

How to handle form data in CGI Scripts?

Last Updated : 04 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we’ll guide you through the process of creating a registration form in HTML and then using a CGI script to fetch and display the submitted user data in the form of a card, along with a success message. Registration forms are a fundamental component of many web applications, allowing users to provide essential information for access or membership. By integrating CGI scripts, we can capture and process this data, enhancing user interactivity and providing a seamless user experience.

Handle Form Data in CGI

Below are the steps by which we can handle form data in CGI Scripts:

Step 1: Implementation

First, create a folder named “form” in the “htdocs” directory. Inside this “form” folder, create two files: “html.html” and “python.py”. In the “html.html” file, design the registration form. In the “python.py” file, write a CGI script to retrieve data from the registration form and generate a card with a success message.

File structure

mgbgjbjgwer

File Structure

Step 2: Write HTML Code (html.html)

Now we will write our HTML file code in which we are creating a form that will be used to handle the form data using CGI Script. This code creates a registration form with basic styling using CSS. When users submit the form, the data will be sent to a server-side script specified in the “action” attribute of the form for processing.

HTML




<!DOCTYPE html>
<html>
<head>
    <title>Registration Form</title>
    <style>
        /* Style for the "GeeksforGeeks" heading */
        h1 {
            color: green;
        }
 
        /* Style for the form container */
        .form-container {
            padding: 20px;
            margin: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }
 
        /* Style for form labels and input fields */
        label {
            display: block;
            margin-bottom: 10px;
        }
 
        input[type="text"],
        input[type="email"],
        input[type="password"] {
            width: 30%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }
 
        input[type="submit"] {
            background-color: green;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>GeeksforGeeks</h1>
    <div class="form-container">
        <h2>Registration Form</h2>
        <form action="python.py" method="post">
            <label for="name">Name:</label>
            <input type="text" name="name" required><br><br>
 
            <label for="email">Email:</label>
            <input type="email"  name="email" required><br><br>
 
            <label for="password">Password:</label>
            <input type="password"  name="password" required><br><br>
 
            <input type="submit" name="Register">
        </form>
    </div>
</body>
</html>


Output

registraion

Registration form

Step 3: Write Python CGI Script (python.py)

This is a Python script that acts as a server-side handler for a web form submission. It processes the form data sent from an HTML form and generates an HTML response to confirm the registration. Here’s an explanation of the code:

Retrieving Form Data:

  • name = form.getvalue(‘name’): Retrieves the value of the ‘name’ field from the submitted form.
  • email = form.getvalue(’email’): Retrieves the value of the ’email’ field from the submitted form.
  • password = form.getvalue(‘password’): Retrieves the value of the ‘password’ field from the submitted form.

In summary, this Python script processes form data, extracts values, and generates an HTML response to confirm the registration, including the user’s name, email, and a success message.

Python3




#!C:\Program Files\Python311\python.exe
 
print("Content-type: text/html\n\n")
import cgi
 
# Get form data
form = cgi.FieldStorage()
 
# Retrieve values from the form
name = form.getvalue('name')
email = form.getvalue('email')
password = form.getvalue('password')
 
# HTML response
print("<html>")
print("<head>")
print("<title>Registration Confirmation</title>")
print("<style>")
print("  /* Style for the card container */")
print("  .card {")
print("    width: 300px;")
print("    padding: 20px;")
print("    margin: 20px auto;")
print("    border: 1px solid #ccc;")
print("    border-radius: 5px;")
print("    text-align: center;")
print("  }")
print("</style>")
print("</head>")
print("<body>")
print("<div class='card'>")
print("<h2>Registration Confirmation</h2>")
print("<p>Name: " + name + "</p>")
print("<p>Email: " + email + "</p>")
# You should never display passwords like this in a real application; this is just for demonstration purposes
print("<p>Password: " + password + "</p>")
print("<p>Registration Successful! 👍</p>")  # Emoji for success
print("</div>")
print("</body>")
print("</html>")


Output

confirma

CGI scripts

Step 4: Configuration and Start the Xampp Server

You can refer Create a CGI Script for complete configuration and how we can start the server to run out CGI Script.

Step 5: Run the Script

In this step, we will run the CGI Script by using the following command in your web browser

http://127.0.0.1/form/html.html

Output

confirma



Similar Reads

How CGI Scripts recieve data from HTML forms?
In this article, we will see how we can revive the data from HTML forms in CGI Scripts (Common Gateway Interface). We will perform the demonstration on a Windows Operating System machine. We will create a basic HTML form and a CGI script using Python, which will handle the data revived from the HTML form. Related Concepts CGI Script: A CGI script i
5 min read
How To Enable or Disable CGI Scripts in Apache?
This article will guide you on how to enable or disable CGI scripts in Apache. Configuring CGI scripts in Apache is a crucial aspect of managing dynamic content generation on web servers. The Common Gateway Interface (CGI) provides a standardized protocol for executing programs, allowing websites to produce dynamic output. Whether enabling or disab
4 min read
How to generate webpages using CGI scripts?
In this article, we will explore the process of generating webpages using CGI scripts. Furthermore, we will discuss the importance of CGI script implementation in facilitating dynamic content creation. Additionally, we'll delve into the intricacies of linking one page to another by creating multiple pages within Python CGI scripts, ensuring a seaml
4 min read
How to generate basic HTML output using CGI scripts?
In this article, we will explore the process of generating basic HTML output using CGI scripts. Specifically, we will focus on creating a simple HTML web page using Python. The objective is to provide a step-by-step walkthrough, detailing the entire process of creating and utilizing CGI scripts to generate HTML content within a web environment. Wha
3 min read
How to Execute SQL queries from CGI scripts
In this article, we will explore the process of executing SQL queries from CGI scripts. To achieve this, we have developed a CGI script that involves importing the database we created. The focus of this discussion will be on writing code to execute SQL queries in Python CGI scripts. The initial step involves creating a database, and it's worth noti
5 min read
How to Create Form using CGI script
HTML forms are a fundamental part of web development, allowing users to input data and interact with web applications. Web developers often use Common Gateway Interface (CGI) scripts to process and send the data submitted through these forms. In this article, we'll explain what Python CGI scripts are and guide you through how we can create a form u
3 min read
What is CGI in Python ?
CGI stands for Common Gateway Interface in Python which is a set of standards that explains how information or data is exchanged between the web server and a routine script. This interface is used by web servers to route information requests supplied by a browser or we can say that CGI is customary for external gateway programs to interface with in
3 min read
How to create a simple CGI script?
In this article, we will explore how to create a simple CGI (Common Gateway Interface) script on a Windows machine but before that, we need some basic ideas about these technologies ( CGI Script, HTTP, Web Server ).CGI Script: A CGI script is a program that runs on a web server and generates dynamic web content. It's often used for processing web f
2 min read
Historical context and evolution of CGI.
When you click on any of the links on the webpage, your browser contacts the HTTP web server and demands the URL that is, the filename, and the web server passes the URL and looks for the filename, if it finds that file, it will send it back to the browser otherwise sends an indicating message that you have requested a wrong file. Then, the web bro
12 min read
CGI vs Client-Side Scriting ( Javascript)
In the ever-evolving world of web development, two fundamental technologies play a crucial role in enhancing user experiences and enabling dynamic web applications: CGI (Common Gateway Interface) and Client-Side Scripting, often powered by JavaScript. These technologies serve different purposes and have distinct characteristics. In this blog, we'll
3 min read
Emerging technologies and trends in CGI programming
In the ever-evolving global generation, Computer-Generated Imagery (CGI) programming isn't any exception to the rule of thumb. CGI has come a prolonged way due to the fact its inception, and it continues to strengthen at a mind-blowing pace. This article explores the growing era and trends in CGI programming, shedding light on the thoughts, and ste
7 min read
How to generate dynamic content with CGI?
In this article, we will explore how we can generate dynamic content with CGI (Common Gateway Interface) script on a Windows machine. We will create a webpage in which various user interactions can be performed, dynamic data is been displayed as per user input. CGI Script: A CGI script is nothing but a program that is executed on the web server and
4 min read
Handling File Uploads via CGI
In this article, we will explore how we can handle file uploads via CGI (Common Gateway Interface) script on Windows machines. We will develop a form in which there will be the functionality of uploading the file, when the user uploads the file and submits the form, the data is been passed to the CGI script and the file that is uploaded will get st
6 min read
What is the role of CGI in Web development?
CGI stands for common gateway interface. It is an interface that enables the web server to process a user's HTTPS request by executing a program. It executes a program that resides on the server to process data to produce the relevant dynamic content. When a client gives a request or input, this data is passed to the CGI script as an environment va
6 min read
GET and POST in Python CGI
In this article, we will explore the GET and POST methods in CGI. In Python, the Common Gateway Interface (CGI) plays an important role as it enables and helps in the creation of dynamic web pages. It basically allows Python scripts to be executed and run on a web server in response to a client's HTTP request. if you are learning networking for the
5 min read
CGI Programming in Python
What is CGI? Common Gateway Interface (also known as CGI) is not a kind of language but just a specification(set of rules) that helps to establish a dynamic interaction between a web application and the browser (or the client application). The CGI programs make possible communication between client and web servers . Whenever the client browser send
5 min read
Command Line Scripts | Python Packaging
How do we execute any script in Python? $ python do_something.py $ python do_something_with_args.py gfg vibhu Probably that's how you do it. If your answer was that you just click a button on your IDE to execute your Python code, just assume you were asked specifically how you do it on command line. Let's make it easier for you. $ do_something $ do
4 min read
Running Extra scripts in Django
Running extra scripts or processes is always needed when you have some new idea that works with web development and in Python!!! it is always.It can be any script that may include a loading of data, processing, and cleaning of data, or any ML phase when making an application providing business logic directly in views or models is not always best. A
2 min read
How to Schedule Python Scripts As Cron Jobs With Crontab
In this article, we will discuss how to schedule Python scripts with crontab. The Cron job utility is a time-based job scheduler in Unix-like operating systems. Cron allows Linux and Unix users to run commands or scripts at a given time and date. One can schedule scripts to be executed periodically. The crontab is a list of commands that you want t
3 min read
Scheduling Python Scripts on Linux
Sometimes we need to do a task every day, and we can do these repetitive tasks every day by ourselves, or we can use the art of programming to automate these repetitive tasks by scheduling the task. And today in this article we are going to learn how to schedule a python script on Linux to do the repetitive tasks. We are going to a utility called c
3 min read
Importing Python Functions from Other Scripts
Modular programming in Python enables reuse and structure of code. To accomplish this, importing functions from other scripts or modules is a potent method. This procedure facilitates collaborative development, promotes concern separation, and improves code readability. The ideas and procedures involved in importing Python functions from one script
3 min read
Remove all style, scripts, and HTML tags using BeautifulSoup
Prerequisite: BeautifulSoup, Requests Beautiful Soup is a Python library for pulling data out of HTML and XML files. In this article, we are going to discuss how to remove all style, scripts, and HTML tags using beautiful soup. Required Modules: bs4: Beautiful Soup (bs4) is a python library primarily used to extract data from HTML, XML, and other m
2 min read
Top 12 Python Scripts For Developers to Implement
Python is a widely used high-level, general-purpose programming language.  This language can be used in web development, machine learning applications, and all cutting-edge software technology and is preferred for both beginners as well as experienced software developers. Developers spent most of their time developing or working with scripts. Pytho
11 min read
Handle mouse events in Python - OpenCV
OpenCV is one of the most popular computer vision libraries. If you want to start your journey in the field of computer vision, then a thorough understanding of the concepts of OpenCV is of paramount importance. Note: For more information, refer to Introduction to OpenCV Handling Mouse Evenets OpenCV sometimes helps to control and manage different
2 min read
How to handle alert prompts in Selenium Python ?
Selenium’s Python Module is built to perform automated testing with Python. Alerts are a way to show popups in the browser for either accepting data or displaying data. Selenium provides methods to handle alerts of all kinds. class selenium.webdriver.common.alert.Alert(driver) handles all alerts in Selenium Python. It contains methods for dismissin
2 min read
How to handle invalid arguments with argparse in Python?
Argparse module provides facilities to improve the command-line interface. The methods associated with this module makes it easy to code for command-line interface programs as well as the interaction better. This module automatically generates help messages and raises an error when inappropriate arguments are passed. It even allows customizing the
4 min read
How to handle a Python Exception in a List Comprehension?
An exception is something that interrupts the flow of the program. These exceptions stop the process running and sends out an error message. Exceptions can be simply viewed as an object that represents an error. There are predefined exceptions and user-defined exceptions in Python. In this article, we will discuss how to handle Python exception in
5 min read
How to handle Frames/iFrames in Selenium with Python
Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python. HTML outlines are utilized to isolate your program window into numerous segments where eac
2 min read
Flask HTTP methods, handle GET & POST requests
In this article, we are going to learn about how to handle GET and POST requests of the flask HTTP methods in Python. HTTP Protocol is necessary for data communication. In the context of the World Wide Web, an HTTP method is a request method that a client (e.g. a web browser) can use when making a request to a server (e.g. a web server). There are
6 min read
How to handle missing values of categorical variables in Python?
Machine Learning is the field of study that gives computers the capability to learn without being explicitly programmed. Often we come across datasets in which some values are missing from the columns. This causes problems when we apply a machine learning model to the dataset. This increases the chances of error when we are training the machine lea
4 min read