Broad Network


Registration Perl File for Web Development with MySQL

Web Development Basics with Perl and MySQL – Part 7

Using Apache Web Server

Foreword: In this part of the series, I talk about the Perl script that responds to the registration of a member.

By: Chrysanthus Date Published: 28 Apr 2016

introduction

This is part 7 of my series, Web Development Basics with Perl and MySQL. In this part of the series, I talk about the Perl script that responds to the registration of a member. I assume you have read the previous parts of the series, before reaching here; this is a continuation. I will talk about the login script in the next part of the series.

The name of the script is, register.pl. In this project, the script is in the home directory. The script connects to the database as the root: The script attempts to create the user account. If it does not succeed, it informs that user (student) that the user name already exists – precisely it tells him that he should change the user name and try again. If this step is successful, it goes on to give the new user privileges, in some tables of the Bookshop database. After that it selects the Bookshop database and inserts a row of the user’s credentials in the Members table. After that it sends an email to the member’s email box, informing him that his membership request has been accepted.

In my computer, the home directory where the file is saved is, C:\Program Files\Apache Software Foundation\Apache2.2\htdocs. Your computer should have a similar directory where the files are saved.

Note, before you can test any code, the MySQL server and the Web Server have to be on and running.

We now look at the different code segments of the Perl script.

The First Code Segment
The very first code segment is:

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

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

The very first line brings in the famous Mysql module (API) for communication with the MySQL database server. The second line brings in the CGI module for receiving the data (credentials) sent from the client browser. The third line permits only strict coding in the Perl script you are to produce. The fourth line sends the argument of all print statements back to the client’s browser.

Note, with Apache server, whether you are using the Windows Operating system or not, the line like “#!C:/Perl/bin/perl5.18.2.exe” should be in the script.

The Second Code Segment
This second code segment of the script is:

    my $obj = CGI->new();

    my $username = $obj->param('username');
    my $password = $obj->param('password');
    my $firstname = $obj->param('firstname');
    my $middlename = $obj->param('middlename');
    my $lastname = $obj->param('lastname');
    my $email = $obj->param('email');
    my $phone = $obj->param('tel');
    my $university = $obj->param('university');
    my $address = $obj->param('address');
    my $city = $obj->param('city');
    my $state = $obj->param('state');
    my $country = $obj->param('country');

    my $continue = "Yes";

It starts with the creation of the CGI object. From the object, the user name, password and other credentials are taken and assigned to respective variables. Then you have the definition of the $continue variable. This variable is initialized with "Yes". If the script fails to connect, it will set this variable to "No", and that will prevent its lower script part from executing. If the script fails to create a user account, it also sets this variable to "No", to prevent its lower part from executing. You will have more explanation on this as you read the code segments below.

The Third Code Segment
This is the third code segment:

    if (!Mysql::connect("root", "xxxxxx", "localhost", 3306))
        {
            print "<body><h3>" . $Mysql::Error_msg . "</h3></body>";
            $continue = "NO";
        }
    else
        {

This segment attempts to connect to the database server (the database server is different from the web server). If it fails, it sends an error message to the user and sets the value of the $continue variable to NO. If it succeeds, it executes all the code in its else-block.

The Fourth Code Segment
This is the fourth code segment:

            my $createUserStr = "CREATE USER '$username' IDENTIFIED BY '$password'";  
            if (!Mysql::query($createUserStr))
                {
                    print "<body><h3>" . $Mysql::Error_msg ."</h3></body>";
                    $continue = "NO";
                }
            else
                {#if the user has been created, then this segment will likely be executed

MySQL 5 can have only one user with a particular name. However, it can have different users with the same password. This code segment attempts to create a user. If is fails it sends a feedback to the user, telling him to change his user name and try again. If it succeeds, its else-block is executed. Its else-block is the following segment explained:

The Fifth Code Segment
This is the fifth code segment:

            else
             {//if the user has been created, then this segment will likely be executed

                    my $grantStr1 = "GRANT INSERT, SELECT ON Bookshop.Members TO '$username'";
                    my $grantStr2 = "GRANT SELECT ON Bookshop.Products TO '$username'";
                    my $grantStr3 = "GRANT INSERT, SELECT ON Bookshop.Sales TO '$username'";
                    my $grantStr4 = "GRANT INSERT ON Bookshop.SaleItems TO '$username'";
        
                    Mysql::query($grantStr1);
                    Mysql::query($grantStr2);
                    Mysql::query($grantStr3);
                    Mysql::query($grantStr4);

                    Mysql::select_db("Bookshop");

                    my $credentialsStr = "insert into Members (username, email, phone, firstname, middlename, lastname, university, address, city, state, country) values (\"$username\", \"$email\", \"$phone\", \"$firstname\", \"$middlename\", \"$lastname\", \"$university\", \"$address\", \"$city\", \"$state\", \"$country\")";
                    Mysql::query($credentialsStr); #if the user was succesfully created then this correct syntax line should work, unless the table is full.
             }

This segment gives the new user certain privileges to certain tables in the Bookshop database. Then it adds a row of the new user’s credentials to the Members table in the Bookshop database.

The Sixth Code Segment
This is the sixth code segment:

            #success feedback to user
            if ($continue eq "Yes")
             {
                    print "<body><h3>congratulations! Your user account has been created. You can now login and make good use of the site.</h3></body>";
             }

            Mysql::close();

        }

If at this point in the script, the value of the $continue variable is still “Yes”, then it means a new user account has been created with all the credentials stored in the database. This last segment checks if the value of the variable is “Yes”. If it is, then it sends a feedback to the user, informing him that his account has been successfully created. After that it closes the connection. Above, the segment ends with the closing } for the connection if-else-block

In practice the congratulatory message here should be typed in the email section, along side the successful sending of the email (see below).

The Email to New User

Before the “Mysql::close();” line in the code, or below it, but still in the connection else block, you can add email code that will send an email to the user (student) informing him of his successful registration. The skeleton of the code is:

    if ($continue == "Yes")
        {
            #compose email in its right format and send.
        }

In this section Perl will prepare the email in its technical format and send to the email box of the user. If the email does not go to the box, Perl will prepare a whole web page with the error message and send to the client’s browser. If the email goes to the box, Perl will still prepare a whole web page with the confirmation message and send to the client’s browser.

Date-Time
As you saw in one of the previous parts of the series, the email date-time has to be presented in a particular format. The Perl code to do that is:

                    my @time = localtime();
                    my @week = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
                    my @mYear = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

                    my $serverDateStr;

                    my $year = 1900 + $time[5];
                    my $hr = $time[2];
                    my $mn = $time[1];
                    my $sc = $time[0];
                    if (length($hr) == 1)
                        {
                            $hr = "0" . $hr;
                        }
                    if (length($mn) == 1)
                        {
                            $mn = "0" . $mn;
                        }
                    if (length($sc) == 1)
                        {
                            $sc = "0" . $sc;
                        }
                    $serverDateStr = $week[$time[6]] . ", " . $time[3] . " " . $mYear[$time[4]] . " " . $year . " " . $hr . ":" . $mn . ":" . $sc;

You will just have to search my blog, using the Search Box of the tutorial above, to know how the code came about.

Wrapping User Sent Message
The email structure is divided into the header block and the body block. In the body block, no line should be more than 78 characters. The following code wraps the user sent message into a maximum of 78 characters per line:

    my $msgVal = "Hello,\nCongratulations! Your request for membership has been accepted.\nThe Boss";    my $msgVal = "Hello,\nCongratulations! Your request for membership has been accepted.\nThe Boss";
sub textWrap
    {
        $msgVal  =~ s/^ +//; #remove leading space characters
        my @arr = split (/\r\n|\n/, $msgVal); #split at new lines
        my $str = ""; #final string
        foreach (@arr)
           {#form the final string inserting \n
                if (length($_) <= 78)
                    {
                        $str = $str. "$_\n";
                    }
                else
                   {#get 12 words sequences ending them with \n
                       while ($_ =~ /(S+( S+){1,11})/g)
                           {
                                $str = $str . $1 . "\n";
                           }
                   }
            }
        return $str;
    }

This Perl function is typed above the connection if-else-block. You will just have to search my blog, using the Search Box of the tutorial above, to know how the code came about.

The Complete Email Message String
The date-time code is placed in the email section in the register.pl script. The textWrap() function is placed above the connection if-else block. The following code, which produces the complete email message, is placed inside the email section of the register.pl script. Remember, the whole email text sent to the destination email box has to be in a particular email format.

    my $wrappedText = textWrap();
    my $emailMessage = "From: <boss\@company.com>\nTo: <$email>\nSubject: Membership Request\n$serverDateStr -0000\n\n$wrappedText";

You will just have to search my blog, using the Search Box of the tutorial above, to know how the code came about.

The HTML page to send back in case the email was not sent from the server to the destination, is divided into two halves as follows:

    my $errorTop = "<html>
                    <head>
                    <title>Error</title>
                    </head>
                    <body>
                    <h4>";

and

    my $bottomPage = "</h4>
                     </body>
                     </html>";

If the email went through, then the top of the confirmation page is:

    my $eSent = "<html>
                 <head>
                 <title>Email Sent</title>
                 </head>
                 <body>
                 <h4>";

The bottom of the page is the same as for the error page. The code that actually sends the email and gives feedback to the registering user is as follows:

Actual Code to send Email
The actual code to send the email is:

        open(SENDMAIL, "|/usr/lib/sendmail -oi -t")
                    or die print $errorTop. "Email could not be sent: $!" . $bottomPage;
        print SENDMAIL $emailMessage;
        close(SENDMAIL)     or warn "sendmail didn't close properly";

The code to send back to the user confirming that the email has been sent goes just below this one. If this code (does not die and) sends the email, the code below it will be executed. The code below it is just one line and it is:

        print $eSent. "Email has been sent!" . $bottomPage;

Note: you can join the pieces of code in this tutorial to form the whole Perl file.

The complete register.pl file can be downloaded at the end of the series. Before downloading, you will have to agree that I have produced all the code to the best of my ability and I am not responsible for any problem it might cause to your system.

As I said in one of the previous parts of the series, all the HTML and Perl scripts are in the home directory of the web server. To test the log_reg.htm and register.pl files you will type the following at the address bar of your browser:

    http://localhost/log_reg.htm

When the web page opens, you will see the lower form titled, Register and then click, Send. The register.pl will send the email if your local host operating system is Linux. If you have the Windows Operating system, then you will have to replace the send mail program with the windows’ equivalent. The email will be sent if you are hooked to the Internet.

Note: in practice, the script will have to login with some non-root account that has some root privileges, for security.

That is it for this part of the series. We take a break here and continue in the next part.

Chrys

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