|
First Click here to run this example .
<html><body> <center><h1>Password Protection</h1> <hr> <form method=POST action="cgi-bin/password2.pl"> <table> <tr><td bgcolor="yellowgreen">Your Name: </td> <td> <INPUT NAME="name" TYPE="TEXT" SIZE="10" MAXLENGTH="20"></td> <td> <INPUT TYPE="SUBMIT" VALUE="Submit"> </td></tr> <tr> <td bgcolor="yellowgreen">Your Password:</td> <td><INPUT NAME="password" TYPE="PASSWORD" SIZE="10" MAXLENGTH="20"></td><td> <INPUT TYPE="RESET"></td> </tr></table> </form></center> </body></html>
#!/usr/local/bin/perl
########################################################################
# password2.pl
# 11/26/97 by Zhanshou Yu
# Any comments please send to :
# zhanshou@hotmail.com
########################################################################
#Specify the protected file path and name
$filename="/home/CGITutorial/protectFile";
#Get the system date
$date=`/usr/bin/date`;
chop($date); #chop the last enter character
#Define login name and password.
%PASSWD=('zyu','aaaa',
'cwu','bbbb',
'jeff','cccc');
#get the input data from the form. Here I use POST method
read(STDIN,$buffer,$ENV{'CONTENT_LENGTH'});
#Split the name-value pairs.
@pairs=split(/&/,$buffer);
#for each name=value pair, seperate them.
foreach $pair(@pairs){
($name,$value)=split(/=/,$pair); #split name=value to name value
$value=~tr/+/ /; #substitute plus sign with space sign
$value=~s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg; #decode hexdecimal to cha
$FORM{$name}=$value;
}
# print html header
print" Content-type:text/html\n\n";
$flag=0;
#Check the received login name and password in our list or not, if in, open and read the file.
foreach $item(keys%PASSWD)
{ if(($item eq $FORM{'name'})&& ($FORM{'password'} eq $PASSWD{$item}))
{
$flag=1;
open(FILE," $filename")||die"Cannot open $filename \n";
while(<FILE>){
print;
}
close(FILE);
last;
}
}
#login failed, print error message
if($flag==0)
{
print "<title>Login failed</title>";
print "<center><h1> Login Error </h1></center>";
print "<hr>";
print "<h4> Invalid login name or password!!</h4>";
}
exit;
First we need specify the protected file name:
$filename="/home/CGITutorial/protectFile";
Now let's look at the second red parts:
{ if(($item eq $FORM{'name'})&& ($FORM{'password'} eq $PASSWD{$item}))
{
$flag=1;
open(FILE," $filename")||die"Cannot open $filename \n";
while(<FILE>){
print;
}
close(FILE);
last;
}
}
After receiving login name and password, check whether they match any of pair in the name list:
if(($item eq $FORM{'name'})&& ($FORM{'password'} eq $PASSWD{$item}))
If found a match, open the file:
open(FILE," $filename")||die"Cannot open $filename \n";Then print it line by line:
while(<FILE>){
print;
}
Finally close the file:
close(FILE);