CGI Script example: tell a friend script

 

Just to make it very very clear, do not type in the line numbers in the below example when you create this script on your computer.

 

1     #!/usr/bin/perl –w

2    

3     use strict;

4     use CGI::Carp qw(fatalsToBrowser);

5     use CGI qw(:standard);

6     my $sendmail_path = ‘/usr/lib/sendmail’;

7     my $url = url;

8     my $mode = param(‘mode’);

9     my $site_to_promote = ‘http://expertwebinstalls.com’;

10    if($mode eq ‘’)

11    {

12      # let’s do this one without the fancy CGI.pm html generation

13      print <<MULTILINE_SEPERATOR;

14      Content-type: text/html

15

16      <html>

17      <body>

18      <h2>Tell A Friend About This Site!</h2>

19      <form action=”$url” method=”post”>

20      <table border=”0” cellspacing=”0” cellpadding=”4”>

21        <tr>

22          <td><b>Your Name</b></td>

23          <td><input type=”text” size=”20” name=”your_name”></td>

24        </tr>

25        <tr>

26         <td><b>Your Email</b></td>

27         <td><input type=”text” size=”20” name=”your_email”></td>

28       </tr>

29       <tr>

30         <td><b>Friend’s Name</b></td>

31         <td><input type=”text” size=”20” name=”friends_name”></td>

32       </tr>

33       <tr>

34         <td><b>Friend’s Email</b></td>

35         <td><input type=”text” size=”20” name=”friends_email”></td>

36       </tr>

37       <tr>

38         <td colspan=”2”><input type=”submit” value=”Send The Email”></td>

39       </tr>

40     </table>

41     <input type=”hidden” name=”mode” value=”send_email”>

42     </form>

43     </body>

44     </html>

45   MULTILINE_SEPERATOR

46      }

47      elsif($mode eq ‘send_email’)

48      {

49        my $your_name = param(‘your_name’);

50        my $your_email = param(‘friends_name’);

51        my $friends_name = param(‘friends_name’);

52        my $friends_email = param(‘friends_email’);

53        my $email_subject = $your_name . ‘ Recommends you visit ‘ . $site_to_promote;

54        my $email_body = <<SOME_TEXT;

55      Dear $friends_name,

56

57      This is $your_name.  I just wanted to tell you about

58      This great site I’m at right now.  Go check it out at:

59

60      $site_to_promote

61

62      Regards,

63      $your_name

64      SOME_TEXT

65        my $message = <<MESSAGE_SEPERATOR;

66      From: $from_email ($from_name)

67      Subject: $email_subject

68      To: $to_email ($to_name)

69     

70      $email_body

71      MESSAGE_SEPERATOR

72        if($email_address =~ /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/ || $email_address !~ /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/) { die(‘Invalid Email Address’) }

73        # the preferred way to do it

74        open (PIPE_TO_SENDMAIL, "| $sendmail_path –t oi”);

75        # some not so smart web hosts only let this work like the following:

76        #open (PIPE_TO_SENDMAIL, "| $sendmail_path –t”);

77        # some rather idiotic web hosts only let it work like this:

78        #open (PIPE_TO_SENDMAIL, "| $sendmail_path $email_address”);

79        print PIPE_TO_SENDMAIL $message;

80        close(PIPE_TO_SENDMAIL);

81        Print header,

82        Start_html,

83        H2(‘Message Sent To Friend Successfully!’),

84        End_html;

85      }

86      else

87      {

88        print header,

89        start_html,

90        h2(‘Bad Mode Specified.  Exiting…’),

91        end_html;

92      }

 

Line 1: Initialize the perl interpreter to run our program, and pass it the warn flag so we get good errors for debugging.

Line 2: Always put an empty line after calling perl.

Line 3: Enable more useful error messages for debugging.

Line 4: Load the module that turns cryptic 500 Internal Server Errors into useful error messages we can read in a web browser.

Line 5: Load the CGI module and import it’s functions, which saves us tons of time and effort in writing cgi scripts.

Line 6: Define a scalar string variable that tells the program where the sendmail program is located on our system.  If you don’t know where this is, ask your sysadmin or web hosting provider.

Line 7: Define a scalar string variable that is assigned the value of CGI.pm’s url function, which gives us the url of the currently running script.

Line 8: Define a scalar string variable, and assign it the value of CGI.pm’s param function, passing the param function an argument of ‘mode’.  This gets the value for the CGI name/value pair with the name of ‘mode’.

Line 9: Define a scalar variable to store the URL of the web site we want visitors to be telling their friends about.  In this case, I’ll set the value to that of my web site.

Line 10: Begin an if statement, testing to see if the $mode variable we set above is currently empty.

Line 11: Use an open bracket to define the beginning of the scope of the above if statement.

Line 12: A comment

Line 13: Begin a multiline print delimiter.

Line 14-44: An HTTP header, followed by a bunch of html, defining a web page and an html form.

Line 45: Ends the multiline print delimiter we started on Line 13.

Line 46: Ends the if statement we started on lines 10 and 11.

Line 47: Begin an elsif statement, testing to see if the $mode variable contained the string value of ‘send_email’

Line 48: The opening bracket to the above elsif statement.

Line 49: Define a variable and assign it the value of the CGI name/value pair for ‘your_name’.

Line 50: Define a variable and assign it the value of the CGI name/value pair for ‘your_email’.

Line 51: Define a variable and assign it the value of the CGI name/value pair for ‘friends_name’.

Line 52: Define a variable and assign it the value of the CGI name/value pair for ‘friends_email’.

Line 53: Define the subject of the email we want to send later.  We concatenate the value of the person’s friends name and the site to promote into this string so that it is more well-accepted by the friend who receives the email.

Line 54: Define a variable called $email_body, and fill it with some text typed inside a multiline text separator.

Lines 55-63: The text we want to send to the person’s friend, with variables we defined above interpolated in.

Line 64: End the multiline text separator that defined the text for the $email_body variable we started on line 54.

Line 65: Begin a scalar variable that uses the multi-line print statement delimiter.  This works just as if you were passing it to the print function, except that the text you enter into the multiline delimiter is stored in the scalar variable you specifiy, in this case $message.

Line 66: This is the email From field.  We then specify the email address and name of the person the email is coming from.

Line 67: This is the email Subject field.  We get the value for the $email_subject variable from when we defined it at line 53.

Line 68: This is the email To field.   We then specify the email address and name of the person the email is coming from.

Line 69: This is a blank line, and MUST EXIST before we begin the body of the message.  If you don’t have two line breaks before beginning the body of the message, your email will not send properly.  VERY IMPORTANT!

Line 70: This is the $email_body variable we defined above, which contains the body of the message to be sent.

Line 71: This is the delimiter we use to close the multi line variable value assignment we started on line 65.

Line 72: This is what is called a perl ‘regular expression’, and validates that the email conforms to the standard syntax for an email address.  If it does not, the program exits with an error message.

Line 73: This is a perl comment, and doesn’t do anything

Line 74: This opens the sendmail program on our server, using a similar syntax as when we open a file.  The difference is that we use what is a called a “pipe” to the sendmail program, which allow us to send data to the program.  We pass the path of sendmail we defined earlier, and some parameters to the sendmail program.  The –t tells sendmail to use the To field in the email to send the mail, and the oi are extra security related parameters that are wise to include.  Not all web hosts will let you pass parameters to sendmail, so I’ve listed three different ways of invoking sendmail in this example.

Line 75: Another perl comment

Line 76: This opens a pipe to sendmail as well, and you should use this if the program did not work with the syntax outlined on line 74.  This is a little less secure than the version on line 74, but we can only work with what our web hosting service gives us – it’s the best we can do.

Line 77: Another perl comment.

Line 78: This opens a pipe to sendmail as well, and you should use this if the program did not work with the syntax outlined on line 74 or line 76.  This is MUCH less secure than the version on line 74, but we can only work with what our web hosting service gives us – it’s the best we can do.  However, if it comes down to using this method, you need to be very careful to validate the $email_address variable using the syntax on line 72 to be sure someone is not trying to pass a rogue command to your server.

Line 79: This prints the $message variable which contains the full email message we have built to the open sendmail pipe;

Line 80: This closes the pipe to sendmail and effectively sends the message.

Line 81: This begins a multiline print statement, passing as the first argument CGI.pm’s header function, which tells the web server that an html document is on its way out to the web browser.

Line 82: Pass another argument to print, the CGI.pm function for generating the html code to begin an html document.

Line 83: Pass one more argument to the print function, the CGI.pm function for generating an <h2> html tag.  Pass the h2 function a string to notify the user that email was successfully sent, and to whom.  We use string concatenation in the argument to the h2 function, so that we can print out the value of the CGI.pm function paraminside the <h2> tag as well.

Line 84: End our multiline print function with the CGI.pm function to output the end of an html document.  The semicolon tells perl to stop printing, which we began on line 81.

Line 85: End the elsif statement with a closing bracket.  We started this elsifstatement on line 47.

Line 86: Begin an else statement, to catch the case where someone specified a bad mode, perhaps a cracker trying to hack our script and cause the server harm.

Line 87: This begins a multiline print statement, passing as the first argument CGI.pm’s header function, which tells the web server that an html document is on its way out to the web browser.

Line 88: Pass another argument to print, the CGI.pm function for generating the html code to begin an html document.

Line 89: Pass one more argument to the print function, the CGI.pm function for generating an <h2> html tag.  Pass the h2 function a string to notify the user that a bad mode was specified.

Line 90: End our multiline print function with the CGI.pm function to output the end of an html document.  The semicolon tells perl to stop printing, which we began on line 87.

Line 91: This closing bracket tells perl we are finishing our else statement we started on line 86.

 

 


Please rate this cgi tutorial on cgi-resources.com:

CGI-Resources Rating:


Ecommerce Shopping Cart Software
ShopCMS Paypal Shopping Cart
Free CGI Scripts
CGI Tutorial
Software Engineering Consultant
Search Engine Optimization Tips
How To Choose Quality Web Hosting
Free Search Engine Ranking Software
HTTP Compression
Install CGI Scripts
Tell A Friend Script
LittleFTP Free FTP Client For Windows


Link To
This Page!


Copy the following code and paste it into your html file.
Ecommerce Shopping Cart Software | ShopCMS Paypal Shopping Cart | Software Engineering Consultant | Free Search Engine Ranking Software | HTTP Compression | Install CGI Scripts | Search Engine Optimization Tips | CGI Tutorial | CGI Scripts | How To Choose Quality Web Hosting | Tell A Friend Script