Utkarsh Atri Utkarsh Atri - 1 month ago 8
HTML Question

Using perl CGI.pm through multiple subroutines

So I am working on a school project where I have been asked to write perl cgi script to create a social net site.

I have created multiple subroutines for different pages, but my problem is that when I try to execute each subroutine individually, it works fine, but when i try to run it though some other subroutine, it just redirects me to my first page.

For eg : This is my New User page code :

#!/usr/bin/perl -w
use CGI qw/:all/;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
my $cgi = new CGI;

sub main() {
print page_header();

warningsToBrowser(1);

first();

page_trailer();
}


sub page_header {
return header(-charset => "utf-8"),
start_html(-title => 'Matelook',-style => "matelook.css"),
body({-background =>"background.jpg"}),
div({-class => "matelook_heading"}, "matelook");
}

sub page_trailer {
my $html = "";
$html .= join("", map("<!-- $_=".param($_)." -->\n", param())) if $debug;
$html .= end_html;
return $html;
}

sub new_user {
$fullname = param("fullname") || '';
$newun = param("newun") || '';
$newpass = param("newpass") || '';
$email = param("email") || '';
$program = param("program") || '';

if(param("Save")){
$data = "full_name=$fullname \n
username=$newun \n
password=$newpass \n
email=$email \n
program=$program \n";


$location = "dataset-medium/$newun";
mkdir $location, 0755;
open($f,'>',"$location/user.txt");
print $f $data;
print $data,"\n";
print "Data Saved !! ";

}

else{
print start_form,"\n";
print "Enter Full Name :\n", textfield("fullname");
print "New Username :\n", textfield('newun'),"\n";
print "New Password :\n", textfield('newpass'),"\n";
print "Email:\n",textfield('email'),"\n";
print "Program:\n",textfield('program'),"\n";
print submit({-name =>"Save",-class => "matelook_button"});
print end_form,"\n";
}
}

sub first{
if(param("New User")){
new_user();
}
else{
print start_form,"\n";
print submit({-class => "matelook_button_first ",-name => 'New User'}),"\n";
print end_form,"\n";
}
}
main();


if I try to call the same subroutine with a subroutine "first" and click the "Save" button, it redirects me to the "First" page through which I called the new_user.

Any help will be appreciated.

Thanks

Answer

Your program has the following structure:

sub new_user {
   if (param("Save")){
      save();
   } else {
      show_input_form();
   }
}

if (param("New User")){
   new_user();
} else {
   show_menu();
}

The problem is that the input form doesn't set pararm('New User'), so you don't end up in new_user when you click Save.


Solution 1:

Add a hidden input with name New User and value 1.


Solution 2:

Change

if (param("New User"))

to

if (param("New User") || param('Save'))

Solution 3:

Change the structure of the program to

if (param("New User")){
   show_input_form();
}
elsif (param("Save")){
   save();
}
else {
   show_menu();
}
Comments