Perl CGI Script

# example.cgi

# An example script written to print a welcome message and the current date $thismonth = ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec') [(localtime)[4]];

print "Content-type: text/html\n\n";

print "<html><title>This is a CGI script test</title>\n<body>\n"; print "<h1>This is a CGI script test</h1>\n"; print "<p>Hello, World.<br/>"; print "Today is: ";

print $thismonth," ",$thisday, " ",1900+$thisyear; print "</p></body></html>"

Note that the first line of the output from a CGI program is a MIME-type header. This is an HTTP header that tells the client what sort of content it is receiving; in the case of this script, the client will be receiving content of the text/html variety. An empty line must follow the header — hence the '\n\n' concluding the line of Perl code including the Content-type declaration. Second, the remaining output is in HTML, a format that the client web browser is expecting and will be able to display.

However, this script is not quite ready for prime time. When the Apache web server starts up, it is running with the permissions of a user separate of that from the user who created the script. Thus the filesystem permissions of the file need to be changed so that it can be read and executed by whatever user the webserver is running as.

chmod a+x example.cgi

The result of viewing http://<servername>/cgi-bin/example.cgi is shown in Figure 16-3.

^ ' : SeeChapt er 2 for more detail on using chmod.

FIGURE 16-3

CGI script output in the browser

FIGURE 16-3

CGI script output in the browser

All should be set. But most of the time when starting out, a CGI program or script will fail, maybe because of a problem with the program itself, or a syntax or logic error. Remember the web server error logs are your friends. More often than not, if anything goes wrong, it will generate a message in the error log. Look there first (/var/log/apache2/error_log). The error_log file contains errors about why something did not work. This could be an error from a PHP script or a Perl script, for example, and you will have to use your skills in these languages to understand what the log files are telling you.

Learn to read and manage the error (and access) logs that the web server creates, and you will find that almost all the problems are quickly identified and solved.

We discuss Apache logs in Chapter 7.

Was this article helpful?

0 0

Post a comment