Perl - CGI

perl

What is the typical way to create a CGI object?

use CGI;
$query = new CGI;

How can we create a CGI object from a hash?

$query = new CGI({
    'dinosaur' => 'barney',
    'song' => 'I love you',
    'friends' => [qw /Jessica, George, Nancy/]
});

How can we create a CGI object from a query string?

$query = new CGI('dinosaur=barney&color=purple');

How can we create a CGI object from a file?

$query = new CGI(FILEHANDLE); // read parameter from a file handle

open(IN,"test.in") || die("Unable to open test.in");
while (! eof(IN)) { // reload multiple records into an array of queries
    my $q = new CGI(IN);
    push @queries,$q;
}

open(IN,"test.in") || die("Unable to open test.in");
restore_parameters(IN); //read parameters from a file

How can we clone a CGI object?

$old_query = new CGI;
$new_query = new CGI($old_query); // clone

How can we create an empty CGI object?

$empty_query = new CGI('');

How can we get a list of keywords from a CGI object?

@keywords = $query->keywords        // get a list of keywords
@names = $query->param;    // get a list of named parameters

How can we get the value(s) for a particular parameter?

@values = $query->param('foo');
$value = $query->param('foo');

If a value is not given in a query string, it will be returned as an empty string (not undef)

How can we set value(s) for a parameter?

$query->param('foo','value1','value2','value3'); // settings multiple values for foo
$query->param(-name => 'foo', -values => ['value1','value2','value3']); // dido

How can we append value(s) to an existing parameter?

$query->append(-name => 'foo', -values => ['yet','more','values']);

How can we delete a parameter?

$query->delete('foo');

How can we delete all parameters?

$query->delete_all();

How can we persist a CGI object to a file?

$query->save(FILEHANDLE);
save_parameters(FILEHANDLE);

How can we create a URL from a CGI object?

$my_url = $query->self_url;     // This call returns a URL that when clicked reinvoke 
                        // the script with all of its state information intact

$my_url = $query->url;        // Returns a URL without entire query string appended to it

How can we retrieve the value for a URL parameter when the form is a POST-mixed form?

$color = $query->url_param('color');

If we have a situation where the form is submitted using POST method, and the particular parameter that we want to access may or may not be in the POSTed data but is appended to the URL like a normal GET parameter, then we would use the url_param method as shown above.

How can we use the CGI object to output HTML?

$field = $query->textfield(
    -name => 'state',
    -default => 'gaseous',
    -justification => 'right'
);

print $field;
<input type='text' name='state' value='gaseous' justification='right'>

print $query->start_html(
    -title => 'Secret of Pyramids',
    -author => 'fred@capricorn.org',
    -base => 'true',
    -meta => {'keywords' => 'Pharoh secret mummy', 'copyright' => 'Copy right statement'},
    -style => {'src' => '/style/style.css'}
);

print $query->start_html(
    -title => 'Secret of Pyramids',
    -xbase => 'http://www.nile.org'
);
// The xbase parameter points to an external base location
// The target parameter specifies the targeted frame

print $query->start_html(
    -title => 'The riddle of sphinx',
    -script => { -language => 'JavaScript', -src => '/javascript/sphinx.js' }
);

print $query->start_html(
    -title => 'The riddle of sphinx',
    -script => $JSScript,
    -onload => 'riddle_me_this()'
);

print $query->end_html;

print $query->start_form($method, $action, $encoding)
... various form elements
print $query->endform;

print $query->textfield(
    -name => 'fieldname',
    -default => 'starting value',
    -size => 50,
    -maxlength => 80
);

print $query->textarea(
    -name => 'foo',
    -default => 'starting value',
    -rows => 10,
    -columns => 50
);

print $query->password_field(
    -name => 'secret',
    -value => 'starting value',
    -size => 50
);

print $query->filefield(
    -name => 'uploaded_file',
    -default => 'starting value',
    -size => 50,
    -maxlength => 80
);

print $query->startform($method, $action, $CGI::MULTIPART); // start multipart form needed for file uploading
print $query->startform($method, $action, $CGI::URL_ENCODED); // start a url-encoded form

print $query->popup_menu(
    -name => 'menu_name',
    -values => [qw/enie meenie minie/],
    -labels => {'eenie' => 'one', 'menie' => 'two', 'minie' => 'three'},
    -default => 'meenie'
);

print $query->scrolling_list(
    -name => 'listname',
    -values => ['eenie', 'meenie', 'minie','moe'],
    -defaults => ['eenie', 'moe'],
    -size => 5,
    -multiple => 'true',
    -labels => \%labels
);

print $query->checkbox_group(  // creates a group of check boxes with the same name
    -name => 'group_name',
    -values => ['eenie', 'meenie', 'minie', 'moe'],
    -defaults => ['eenie', 'moe'],
    -labels => \%labels,
    -rows => 2,
    -columns => 2
);
// -row_headers and -col_headers accept a pointer to an array of headings to use.

print $query->checkbox(  // creates a stand-alone check box
    -name => 'checkbox_name',
    -checked => 'checked',
    -value => 'Turned on',
    -label => 'Turn me on'
);

print $query->radio_group(
    -name => 'group_name',
    -values => ['eenie', 'meenie', 'minie'],
    -default => 'meenie',
    -linebreak => 'true',
    -labels => \%labels
);

print $query->submit(
    -name => 'button_name',
    -value => 'value'
);

print $query->reset();
print $query->defaults('button label'); // reset to default button

print $query->hidden(
    -name => 'hidden_name',
    -default => ['value1','value2', 'value3']
);

$query->param('hidden_name', 'new', 'value', 'here');
print $query->hidden('hidden_name');

print $query->image_button(
    -name => 'button_name',
    -src => '/images/nyny.gif',
    -align => 'middle'
);

print $query->button(
    -name => 'button1',
    -value => 'Click me',
    -onClick => 'doButton(this)'
);

print $query->image_button(); // creates an image button that act as a submit button

How can we use the CGI object to output HTTP header?

print $query->header('image/gif');
print $query->header('text/html');
print $query->header(-type => 'image/gif', -status => '204 No response');
print $query->header(
    -type => 'image/gif',
    -status => '402 Payment required',
    -expires => '+3d',
    -cookie => $my_cookie,
    -charset => 'UTF-8',
    -attachment => 'foo.gif'
    -cost => '$0.02'
);

How can we use the CGI object to redirect?

print $query->redirect('http://somewhere.else/in/the/world');
print $query->redirect(
    -location => 'http://somewhere.else/',
    -nph => 1
);

How can we process file uploaded?

When the form is processed, we can retrieve the entire file name by calling:

$filename = $query->param('uploaded_file');

where the string 'uploaded_file' is the name of the file upload control in the HTML. The file name returned is also the file handle. You can read the content of the file using the standard Perl file reading calls:

while (<$filename>) { print; }

open(OUTFILE, ">>/usr/local/web/users/feedback") || die("Not able to open /usr/local/web/users/feedback");
while ($bytesread = read($filename, $buffer, 1024)) { // binary file
    print OUTFILE $buffer;
}
close($filename);

$fh = $query->upload('uploaded_file'); // returns a file handle, the safe way
$type = $query->uploadInfo($filename)->{'Content-Type'}; // get the mime type of the uploaded file

How can we get the coordinate when the user clicks on an image?

$x = $query->param('button_name.x'); // get the x-coordinate
$y = $query->param('button_name.y'); // get the y-coordinate

What is the purpose of the CGI->compile method?

use CGI();
CGI->compile(':all');

The above code is needed when used with mod_perl, FASTCGI, or other persistent interpreter. The arguments are a list of names or sets, and are identical to those accepted by the use operator.

What is the purpose of the Dump method of the CGI object?

print $query->Dump;

The above code output a list of name-value pairs, useful for debugging.

How can we use CGI to create a cookie?

$cookie = $query->cookie(
    -name => 'sessionID',
    -value => 'xyzzy',
    -expires => '+1h',
    -path => '/cgi-bin/database',
    -domain => '.capricorn.org', // this cookie will be sent to all host on capricorn.org
    -secure => 1
);

The cookie must be incorporated into the HTTP header within string returned by the header method:

print $query->header(-cookie => $cookie); // sending one cookie
print $query->header(-cookie => [$cookie1, $cookie2]); // sending multiple cookies

How can we use CGI to process cookies?

%anwer = $query->cookie('answer'); // retrieve a cookie named 'answer'
$query->cookie();  // without any parameter, returns a list of names of all cookies.

foreach $name ($query->cookie()) {
    print $query->cookie($name);
}

How can we use CGI in a NPH mode?

use CGI(:standard -nph);
CGI->nph(1);
print $query->header(-nph => 1);

The above 3 statements put CGI.pm in the NPH (non-parse header) mode

How can we prepare CGI to work in a FASTCGI environment?

use CGI::Fast;
#!/usr/local/fcgi/bin/perl
use CGI::Fast;
while (new CGI::Fast) {
    print header, 
        start_html("CGI Script"), 
        h1("CGI Script"),
        "Not much to see here",
        hr,
        address(a({href => '/'}, "home page"),
        end_html;
}

How can we prepare CGI to work in a mod_perl environment?

use CGI::Apache;  // needed for Perl previous to 5.003_93

Add this line to httpd.conf:

PerlScript /home/httpd/conf/startup.pl // Preload CGI.pm.

and create the /home/httpd/conf/startup.pl file:

#!/usr/local/bin/perl
use CGI();
CGI->compile(':all');

How can we do server push with CGI?

You are advised to put the script into NPH mode and set $| to 1 to avoid buffer problems:

#!/usr/local/bin/perl
use CGI qw/:psh -nph/;
$| = 1;

print multipart_init(
    -boundary => '_-_-_-here we go!'
);
while (1) {
    print multipart_start(-type => 'text/plain'), "The current time is ", scalar(localtime), "\n", multipart_end;
    sleep(1);
}

How can we avoid DOS attacks?

$CGI::POST_MAX = 1024 * 100; // allow only 100K post
$CGI::DISABLE_UPLOADS = 1;    // no upload allowed

$uploaded_file = param('upload');
if (! $uploaded_file && cgi_errors()) {
    print header(-status => cgi_error());
    exit 0;
}

How can we turn off auto-escaping?

$query->autoEscape(undef);     // Turn off auto-escaping, allow for special HTML character
                        // sequence such as &Acute (A')

How can we turn on auto-escaping?

$query->autoEscape('yes');    // Turn on auto-escaping (on by default), allow for "<click me>"

How can we store a hash inside a cookie?

$cookie = $query->cookie(
    -name => 'sessionInfo',
    -value => \%myhash,
    -expires => '+1h',
    -path => '/cgi-bin/database'
);
%myhash = $query->cookie('sessionInfo');

How can we use the CGI object to output header that target a particular window?

$query->header(-target => 'top'); // Window-Target: top

How can we use the CGI object to output a custom header?

use CGI;
$query = new CGI();
print $query->header(-status => "200 OK", -fxrate => "300");

What are applicable form encoding?

application/x-www-form-urlencoded
multipart/form-data
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License