CGI Scripts
to Create a Website with Interactive Features
Search the Database
This there are 2 scripts in this exercise. The first is a form that asks the user for a last name. The second script searches names_file.txt and returns the information.
search_form.pl
This script asks the user to enter a last name. Save this script in the cgi-bin\ directory. It could also have been written as an HTML document and saved in the htdocs\ directory. (Note: For html change action to action="cgi-bin/search_file.pl") Notice the action attribute of the form calls for a script named search_file.pl
#!/usr/bin/perl#search_form.plprint "Content-type:text/html\n\n"; #Content Headerprint "<html>\n";print "<head><title>Search Form</title></head>\n";print "<body>\n";print "<form method=\"POST\" action=\"search_file.pl\">\n";print "<pre>\n";print "Enter Last Name:<input type=\"text\" name=\"search\" size=\"20\">\n";print "<input type=\"submit\" value=\"Submit\"><input type=\"reset\">\n";print "</pre>\n";print "</form>\n";print "</body>\n";print "</html>\n";search_file.pl
This script will take the information entered on the form, parse it, open names_file.txt and search for a match.
#!/usr/bin/perl#search_file.plread(STDIN, $buffer,$ENV{'CONTENT_LENGTH'});$buffer =~ tr/+/ /;$buffer =~ s/\r/ /g;$buffer =~ s/\n/ /g;@pairs = split(/&/,$buffer);foreach $pair(@pairs){($key,$value)=split(/=/,$pair);$formdata{$key}.="$value";}$search=$formdata{'search'};
open(INFO, "names_file.txt"); # Open db for reading@array=<INFO>;close (INFO);print "Content-type:text/html\n\n"; #Content Headerprint "<html>\n";print "<head><title>Display File Contents</title></head>\n";print "<body>\n";print "<h4>This script displays the contents of names_file.txt.<br>No names means your search returned no results.</h4>\n";foreach $line (@array){if ($line =~ /$search/){($last,$first)=split(/\|/,$line);print "Your search returned: $first $last<br>\n";}}print "</body>\n";print "</html>\n";names_file.txt
If you haven't completed the previous exercises, copy this file to notepad. Save it in the cgi-bin directory as names_file.txt.
Bunyan|PaulSimpson|BartAnderson|PamelaBush|GeorgeNote: If the scripts don't work:
1...Check the shebang line and make sure it is the path recommended by your web host to access the perl interpreter on your server.
2...Be sure to use the Chmod function on your ftp client or file manager to change the permissions of the script to 755
Free Websites
MoonFruit
More websites
Free Website Builders
Yahoo Sitebuilder 2.6
Ucoz
Alleycode HTML
NoteTab Light
Nvu WYSIWYG
Seamonkey Composer
CSE Validator
HTML Kit
Joomla
Web Hosting Services
Web Hosting FAQ
Recommended
Web Hosts



