Broad Network


Login for Web Development Site with Perl and MySQL

Web Development Basics with Perl and MySQL – Part 8

Using Apache Web Server

Foreword: In this part of the series, I talk about login features for the simple web development project with Perl and MySQL.

By: Chrysanthus Date Published: 28 Apr 2016

Introduction

This is part 8 of my series, Web Development Basics with Perl and MySQL. In this part of the series, I talk about login features for the simple web development project with Perl and MySQL. I assume you have read the previous parts of the series, before reaching here; this is a continuation.

To login, the user (student) has to fill in his user name and password in the login Form at the browser. When he clicks the Submit button of the login Form, the dataset (user name and password) will go to the server. Now, do not confuse between the web server and the database server. These are two different software, each with its own directory tree. The web server directories have the HTML and Perl files. The database directories keep the databases and their tables. However, remember that in this project all the Perl script and HTML files are in the home directory of the web server. The login Perl file that the login Form calls (sends data to) is called, “login.pl”.

Functions of the Login File
In this simple project, the login file will receive the user name and the password of the user. It will attempt a connection. If the connection is successful, then it will read the credentials corresponding to the user in a row in the Members table in the Bookshop database. After it has read the credentials, it will add HTML tags to the data and send to the browser. In other words, the data of the credentials are formatted with HTML tags before being sent to the browser. In that way, the data will be well presented.

It is not only the formatted data that will be sent, a whole HTML document will be sent, and the data will be part of the document.

Login – Logout
In this simple project, we are dealing with the home (index) page, the books page, the pens page and the login/registration page. Each of these pages has a menu (horizontal) at its top. In the menu you have the hyperlink with the name (text), Login. Normally, when this login page is clicked, the login/registration page opens (downloaded and displayed at the browser). If the user successfully logs in; that is the login.pl script makes a connection and sends an HTML document with the user’s credentials to the browser, in this project, the Login hyperlink should change to Logout hyperlink. This will make it possible for the user to logout.

At the browser, this user name and password are saved in the client’s computer, using the sessionStorage (web application) technique. As long as the client is using the site (does not stop using the site) in one session, the user name and password will be in his computer. In the session, for any subsequent connection, the web page of the site should read the user name and password from the computer and send to the server. At the server, the relevant Perl script will use these to connect to the database. In the past, this kind of thing was done with cookies. Today, the sessionStorage technique is replacing cookies. We thank the inventor of cookies, all the same.

Back to the article: So, for the browser user (student), there is a session. Actually the session is only at the browser and at the web server, not at the database server. At the server, each time the user wants data from the database, a relevant Perl script has to login to the database server. So, from the point of view of the database server, there are many sessions, while from the point of view of the user, there is only one session.

The start tag of the login form element should actually be,

    <form method='POST' action='login.pl' onsubmit='return saveUP()'>

So when the submit button of the login form is clicked, the function, saveUP() is called. The function is in the following ECMAScript, which is type somewhere up above the Form element.

    <script type='text/ecmascript'>
        function saveUP()
            {
                sessionStorage.username = document.getElementById('username').value;
                sessionStorage.password = document.getElementById('password').value;
                return true;
            }
    </script>

This function saves the username and password of the user in the client computer.

The Logout ECMAScript
After the login has been successfully done, if a page that has the login hyperlink is reloaded or downloaded, the Login link will change to Logout link. You need an ECMAScript for this.

Now, the login.pl script will not only send back the user name and user credentials to the browser. It will also send the datum, "login". This datum will be stored for the session in the client’s computer. The Logout ECMAScript will check if the sessionStorage value, "login", exist, each time the page is reloaded or downloaded. If it exists, it changes the Login hyperlink to Logout hyperlink. The Logout ECMAScript has to be in every page that has the login link.

Note: if the user clicks the Back button at his browser to go to a previous page, the Logout ECMAScript may not go into effect. However, if the user clicks a link in a current page to go back to a previous page, the Logout ECMAScript must go into effect. In this way, the user can logout in any page he ends up with, in a session.

Here is the Logout ECMAScript:

<script type="text/ecmascript">
    if (sessionStorage.login == "login")
      {
         document.getElementById('login').href = "logout.htm";
         document.getElementById('login').textContent = "Logout";
      }
    else
      {
         document.getElementById('login').href = "login-registration.htm";
         document.getElementById('login').textContent = "Login";
      }  
</script>

Note the use of the session storage login variable in the if-condition. Also note how the block of the if-statement changes the properties of the Login Hyperlink. The else block takes care of situations after logout. You should add this code to all the HTML pages in the project (that have the login hyperlink). A good place to put the code is below the header.

There has to be a “logout.htm” file in the home directory of the web server. When the user wants to close the session (as he sees it) he would click the Logout hyperlink. When he clicks the Logout hyperlink, the “logout.htm” document (page) will be downloaded from the server, and be displayed at the browser. The “logout.htm” file will have as a minimum the following script, which is not visible to the user:

<script type="text/ecmascript">
    sessionStorage.login = "";
    sessionStorage.username = "";
    sessionStorage.password = "";
</script>

As you can see, the “logout.htm” file erases all the login data in the client’s computer. From this point, the user can no longer obtain information from the database; that is, no page on the site can read the login data from the user’s computer and log into the database server (at the other end).

Well, I will not discuss the “logout.htm” file any further. If you have the pre-knowledge mentioned at the beginning of this series, then you should know the HTML elements to use in the “logout.htm” file.

The login.pl File
The first segment of the login file is:

#!C:/Perl/bin/perl5.18.2.exe
use Mysql;
use CGI;
use strict;

print "Content-Type: text/html\n\n";

    my $obj = CGI->new();
    my $username= $obj->param('username');
    my $password = $obj->param('password');

This assigns the password and user name from the CGI object to normal variables.

The second code segment is:

    if (!Mysql::connect($username, $password, "localhost", 3306))
        {
            print "<body><h3>" . $Mysql::Error_msg . "</h3></body>";
        }
    else
        {

This segment uses the user account name (of the student) to attempt a connection with the database. If the connection fails, because of say, wrong username and/or wrong password, the segment sends a feedback to the user. If the connection succeeds, then it executes the else part of the if-statement. The rest of the code in this file is in the else-block.

The third segment is:

            #print back the top of the page
            print "<!DOCTYPE HTML>
                 <html>
                 <head>
                     <title>Login at University Bookshop</title>
                     <style type='text/css'>
                         img {width:200px;height:200px}
                     </style>
                 </head>
                 <body>
                 <header>
                     <h1>Logged in at University Bookshop Site</h1>
                     <a href='index.htm'>Home</a> <a href='books.htm'>Books</a> <a href='pens.htm'>Pens</a> <a href='logout.htm' id='login'>Logout</a> <a href='login-registration.htm#register'>Register</a>
                    </header>
                 <article> <h3>Credentials</h3>";

The Perl script has to send a whole HTML document to the user’s browser. And so this segment sends the top half of the HTML document. The top half is a string in the code segment. Note that there is no double quote in the string, in order to avoid conflict with the delimiting double string quotes in Perl script.

The fourth code segment is:

            #select the database
            if (!Mysql::select_db("Bookshop"))
                {
                    print $Mysql::Error_msg, "<br>";
                }
            else
                {
                    my $credentialsSlct = "SELECT username, email, phone, firstname, middlename, lastname, university, address, city, state, country FROM Members WHERE username=\"$username\"";
                    if (!Mysql::query($credentialsSlct))
                        {
                            print "<h3>" . $Mysql::Error_msg . "</h3>";
                        }
                    else
                        {

                            for (my $i=0; $i<$Mysql::No_of_Rows; ++$i)
                                {
                                    foreach (@Mysql::Result[$i])
                                     {
                                         print "User: ", $Mysql::Result[$i]{"username"}, "<br>";
                                         print "Email: ", $Mysql::Result[$i]{"email"}, "<br>";
                                         print "Phone: ", $Mysql::Result[$i]{"phone"}, "<br>";
                                         print "First Name: ", $Mysql::Result[$i]{"firstname"}, "<br>";
                                         print "Middle Name: ", $Mysql::Result[$i]{"middlename"}, "<br>";
                                         print "Last Name: ", $Mysql::Result[$i]{"lastname"}, "<br>";
                                         print "University: ", $Mysql::Result[$i]{"university"}, "<br>";
                                         print "address: ", $Mysql::Result[$i]{"address"}, "<br>";
                                         print "city: ", $Mysql::Result[$i]{"city"}, "<br>";
                                         print "state: ", $Mysql::Result[$i]{"state"}, "<br>";
                                         print "Country: ", $Mysql::Result[$i]{"country"}, "<br>";
                                     }
                                }

                        }

                }

This segment selects the Bookshop database and reads the user’s credentials from a row in the Members table. After reading, it formats the data with suitable HTML tags and sends to the browser.

The fifth code segment is:

            #send the ECMAScript to store the user login data
            print "<script type='text/ecmascript'>
                sessionStorage.login = \"login\";
            </script>";

This segment sends an ECMAScript to the browser page as a string. Note that there is no pure double quote in the string; this is to avoid conflict with delimiting Perl string double quotes. Read through the segment if you have not already done so. At the browser page (document) this ECMAScript will be printed and executed as follows:

    <script type='text/ecmascript'>
        sessionStorage.login = "login";
    </script>

I hope the minimum requirement for the “logout.htm” page mentioned above is now clear to you.

The last segment is:

            //print the bottom of the page
            print "</article>
                </body>
             </html>";

            Mysql::close();

The segment prints the end of the HTML document and closes the connection to the database.

Note, to use the login/registration page, the URK is,

    http://localhost/log_reg.htm

You should now be in the position to create a simple login page response. You can assemble the code segments above to form a file. Well, time to take a break. We stop here and continue in the next part of the series.

Chrys

Related Links

Related Links

Web Development Basics with Perl and MySQL
Perl Validation of HTML Form Data
Page Views with Ajax and Perl and MySQL
Web Live Text Chart Application using Perl and MySQL
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course

BACK NEXT

Comments

Become the Writer's Follower
Send the Writer a Message