Server-Side Web Applications


Earlier in this chapter, JavaScript was presented as a method for developing client-side web applications, applications that are interpreted and executed by the web browser. Server-side web applications are also accessed using a web browser. However, instead of the web browser executing the program, a server-side web application is executed by the web server that is serving the web pages. Here, we are talking about web servers as defined in Chapter 16, such as the Apache Web Server. This section will discuss two server-side web application technologies: CGI and PHP.

The Common Gateway Interface

Common Gateway Interface (CGI) programs, which have had a large role in enabling the web to become the massive data warehouse it has become today, are an example of serverside web applications. On the web, CGI is used to interface external programs with a web server. A CGI program that is called from a web page is executed by the web server, and the CGI program’s output, which usually includes dynamically generated HTML code, is served by the web server back to the requesting web browser. CGI programs are often used for applications that use a database to store data, data that can be entered or queried by filling out web forms; CGI programs usually generate the web forms and parse/validate the data before they are sent to a database management system. Simple CGI programs also function as web page hit counters that display the number of visits to a page and web site guest books. More sophisticated CGI programs are used to run applications such as Wikis, web-based e-mail clients, and e-commerce shopping carts.

CGI programs can be written in any programming language that understands UNIX-style standard input and output and which can access system environment variables; these languages include compiled high-level languages such as C and C++. But most commonly, CGI programs have been written in interpreted languages such as (k)sh, Perl, and Python. Perl has been particularly popular as a CGI language because of its rich and powerful built-in text parsing capabilities. Because they are interpreted languages, programs written in Perl and Python can be prototyped (written and tested) relatively quickly without an intermediate compile step; this is another reason why these languages have been widely used for CGI work. (See Chapters 22 and 23 for more information on Perl and Python, respectively.) This section will provide some simple examples that give a glimpse of what is possible with CGI programs written in Perl and Python.

We will begin with a simple “Hello World” CGI script written in Perl:

 #!/usr/bin/perl -wT print "Content-type: text/html\n\n"; print "<html><head><title>Hello World</title></head>\n"; print "<body>\n"; print "<h2>Hello, world!</h2>\n"; print "</body></html>\n";

Like all Perl scripts, this script begins with #!, which indicates that this is a script. The next part, /usr/bin/perl, is the location (or path) of the Perl interpreter on the web server’s machine. The final part contains optional flags for the Perl interpreter. Warnings are enabled by the -w flag. Special user input taint checking is enabled by the -T flag. These flags help to create more secure Perl scripts, and their use in almost every Perl CGI script is a good habit to get into.

This CGI script is going to generate an HTML page, so the first print command on the second line, print “Content-type: text/html\n\n”;, is needed before anything else is printed. This is a content-type header that tells the receiving web browser what sort of data it is about to receive, in this case, an HTML document. The script then needs to print out all of the HTML that you want to display in the visitor’s browser, so print statements are included for every line of HTML. The next step is to save this file to a CGI script directory that your web server recognizes (see Chapter 16 for Apache CGI support) and adjust the file permissions to make it world-readable and world-executable (typically with chmod 755 filename). If you consult your web server/system administration, they may be able to configure the web server to execute your CGI scripts from your ~/public_html/cgi-bin directory The usual convention is to give the file a .cgi filename extension. When the CGI script is loaded by your web browser, you should see “Hello, world!” displayed in a H2-size HTML header.

Perl’s CGI.pm Module

One of Perl’s most attractive features is a large library of add-on modules, collections of reusable prewritten code that can save programmers the time and trouble of reinventing the wheel. One of these add-on modules is the CGI.pm module that has been part of the Perl standard library for some time. CGI.pm has a number of useful functions and features for writing CGI programs, and its use is preferred by the Perl community Here is the Hello World CGI script again, this time using CGI.pm:

 #!/usr/bin/perl -wT use CGI qw (:standard); print header; print start_html("Hello World"); print "<h2>Hello, world!</h2>\n"; print end_html;

The second line of the script-use CGI qw(:standard);-includes the CGI.pm module before any other code. The qw(:standard) part of this line indicates that we’re importing the “standard” set of functions from CGI.pm.

CGI.pm has important uses, including a number of functions that serve as HTML shortcuts. The functions that we see in the script are header, start_html(), and end_html The header function prints out the “Content-type” header. The start_html() function prints out the <html>, <head>, <title>, and <body> tags. It can also accept several optional arguments, including the page title argument, for example, print start_html(“Hello World”);. The end_ html function prints out the closing HTML tags: </body></html>. By reducing the number of HTML tags that have to be included in the print statements, these CGI.pm functions have at least made the script easier to read.

The next simple Perl CGI script may be useful for a system administrator wishing to monitor a server’s status remotely using a web browser. (Such a script would be for the administrator’s use only, since it can make system information available to the wrong people. The administrator would do well to password-protect this script.)

 #!/usr/bin/perl -w use CGI qw(:standard); $host=$ENV{HTTP_HOST}; $uptime="uptime"; $w='w -s -h'; print header; print start_html("$host Status"); print "<h1>What's happening on $host</h1>"; print "$uptime"; print "<hr>"; print "<pre>$w</pre>"; print end_html;

The script uses UNIX command substitution to assign the text output of the uptime and w commands to the variables $uptime and $w, respectively The script later prints the contents of $uptime and $w to show a web page that contains information on how long the web server machine has been running, the load on the machine, which users are currently logged in, and what those users are doing. In the third line of the script, $host=$ENV{HTTP_ HOST}, the system environment variable HTTP_HOST is accessed and its value assigned the variable $host. HTTP_HOST contains the hostname of the web server machine. The web server sends a series of environment variables to every CGI program it runs. Your CGI program can parse these variables and use the values they contain. Environment variables are stored in a Perl hash named %ENV.

CGI with HTML Forms

A common form of CGI programming handles interaction between user input in an HTML form and a database. HTML forms consist of several input fields, each with a key identifier, and also a submit button that sends the data in a query string that is parsed by a CGI program. The following is a sample CGI program written in Python:

 #!/usr/bin/python import cgi # Required header that tells the browser how to render the HTML. print "Content-Type: text/html\n\n" # Define function to generate HTML form. def generate_form():     print "<HTML>\n"     print "<HEAD>\n"     print "\t<TITLE>Info Form</TITLE>\n"     print "</HEAD>\n"     print "<BODY BGCOLOR=white>\n"     print "\t<H3>Please, enter your name and age.</H3>\n"     print "\t<TABLE BORDER=0>\n"     print "\t\t<FORM METHOD=post ACTION=\     \"python_cgi_demo.cgi\">\n"     print "\t\t<TR><TH>Name:</TH><TD><INPUT type=text \     name=\"name\" ></TD><TR>\n"     print "\t\t<TR><TH>Age:</TH><TD><INPUT type=text name=\     \"age\" ></TD></TR>\n"     print "\t</TABLE>\n"     print "\t<INPUT TYPE=hidden NAME=\"action\" VALUE=\     \"display\">\n"     print "\t<INPUT TYPE=submit VALUE=\"Enter\">\n"     print "\t</FORM>\n"     print "</BODY>\n"     print "</HTML>\n" # Define function display data. def display_data(name, age):     print "<HTML>\n"     print "<HEAD>\n"     print "\t<TITLE>Info Form</TITLE>\n"     print "</HEAD>\n"     print "<BODY BGCOLOR=white>\n"     print name,", you are", age, "years old."     print "</BODY>\n"     print "</HTML>\n" # Define main function. def main():     form=cgi.FieldStorage()     if (form.has_key("action") and form.has_key("name") \     and form.has_key("age")):              if (form["action"].value == "display"):                 display_data(form["name"].value, form["age"].value)     else:              generate_form() # Call main function. main()

Python also has a standard CGI module that is imported in the second line of this program. Most of this program’s work is done by two Python functions: generate_form(), which mainly prints HTML tags to generate a web page containing the HTML form, and display_data(), which generates a web page that simply displays the data (name and age) that were entered in the form.

If you save this script as python_cgi_demo.cgi to a valid web server CGI directory, make it executable (with chmod 755 python_cgi_demo.cgi), and access it using a web browser, the web server will execute the script and produce an HTML form page like the one shown in Figure 27–14.

image from book
Figure 27–14: Python CGI form

Usually, data that is entered in a CGI-generated form like this will be parsed, validated, and passed-in the form of a query-to a database. In this example, when the form’s Enter button is pressed, the name and age variables are passed to the display_data() function to be displayed in a separate web page.

CGI Overhead and Security

A limitation of CGI, which has been recognized from the beginning of CGI use on the web, is the problem of CGI overhead. CGI overhead is a consequence of HTTP being a stateless protocol, which means that a separate CGI process must be initialized for every “hit” from a browser. With very popular web sites, hundreds or thousands of CGI script instances consuming CPU time and memory would quickly bog down the web server machine. Also, when interpreted languages such as Perl and Python are used, there is the performance overhead of the CGI program’s interpreter having to initialize each time the script is called.

Work-arounds for CGI overhead do exist. There is FastCGI (http://www.fastcgi.com), which does not create a new process for every CGI script request but instead uses a single persistent process to handle many requests. Another approach used to deal with CGI overhead for scripting languages is to embed the interpreter directly into the web server as a module, so that scripts can be executed without creating a new process. The Apache web server has a number of these interpreter modules, including mod_perl (http://perl.apache.org) and mod_python (http://www.modpython.org). These web server interpreter modules allow CGI scripts to run many times faster than the traditional CGI facility

Unfortunately, CGI programs have the demonstrated potential to create large security holes in web server hosting systems. If they are carelessly programmed, they may allow people with malicious intent on the web to enter UNIX commands into CGI-processed forms and have these commands executed on your web server machine. There are rules of thumb that you should heed when writing CGI programs to make them as safe as possible:

  1. Avoid giving out too much information about your web site and server host.

  2. If coding in a compiled language like C, avoid making assumptions about the size of user input.

  3. Never pass unchecked remote user input (such as data typed into HTML forms) to a shell command.

PHP: Hypertext Preprocessor

Another well-known server-side scripting language is PHP. Chapter 16 discussed the process of compiling and configuring the PHP interpreter module for Apache. This section will look more closely at the PHP language. PHP began life as a set of Perl scripts and was released as Personal Home Page, a full-fledged, interpreted web scripting language in June 1995 by Rasmus Lerdorf. In 1998, when PHP Version 3 gained attention in the web development community, PHP had become an acronym for PHP: Hypertext Preprocessor. The new development team, led by Zeev Suraski and Andi Gutmans, two Israeli developers at the Technion-Israel Institute of Technology, released PHP 4 in 2000 and PHP 5, which included many feature enhancements, in 2004. PHP is one of the most popular programming languages for implementing web sites, with reportedly over 20 million Internet domains using it. Because of its ease of use compared to Perl and Python, PHP is most often the “P” in LAMP (Linux, Apache, MySQL, Perl/Python/PHP), a prominent group of technologies that have been used together to create web applications such as content management systems, wikis, and online stores (see the later subsection “PHP and MySQL”).

PHP was originally designed for server-side applications in conjunction with a web server. This is in contrast with languages such as Perl and Python, which were meant to be general-purpose languages. So, while PHP scripts can be executed by the web server using the CGI mechanism, they are more often executed through a PHP interpreter module in the web server. Moreover, unlike Perl or Python CGI scripts, PHP language instructions and routines are inserted into HTML documents using special delimiting tags, as is done with JavaScript programs.

PHP, in its syntax, resembles C/C++, Perl, Java, and JavaScript, sharing the same basic set of arithmetic, assignment, comparison, and logical operators as these languages, as well as the same basic set of control structures, such as if-else and loops. PHP has associative arrays (hashes) like Perl and Python and has object-oriented programming features. This tends to ease the learning of PHP for programmers with experience in other scripting languages. Like Perl, PHP uses flexibly typed variables, prefixed with a “$” and able to hold any data type you wish. For a full PHP language reference, see http://www.php.net/manual/en/langref.php.

In Chapter 16, a simple PHP “Hello World” example was shown that incorporated the useful phpinfo() function (see Chapter 16, Figure 16–5). Here is another PHP example:

 <html> <head><title>A Simple PHP Script</title></head> <body> <h1>A Simple PHP Script</h1> <p>Welcome, Internet user from IP address <?php    $remote_ip=$_SERVER['REMOTE_ADDR'];    print $remote_ip; ?>. <p>Make yourself at home. </body> </html>

This PHP “program” is an HTML file with a couple of lines of PHP embedded in it between the <?php and ?> delimiting tags. In the PHP block, the variable $remote_ip is assigned the value of the CGI environment variable REMOTE_ADDR, which is part of the built-in PHP “autoglobal” array, $_SERVER. REMOTE_ADDR holds the numeric IP address of the web browser host. Next, the PHP print command is executed to print the value of $remote_ip to the standard output. The output from the print command is included in-line into the surrounding HTML code. As in Perl, C/C++, and Java, semicolons are required at the end of PHP statements.

If your web server’s PHP interpreter module is set up as shown in Chapter 16, this HTML file will be scanned for PHP code if it has a .php file extension. Unlike CGI scripts, which must be saved to specific CGI-BIN directories that the web server looks in, .php files can be saved anywhere under the web server’s document root. Also, since .php files are essentially HTML files, they do not need execute permissions as CGI scripts do; .php files do, however, need to be made readable by the web server process owner, which is typically nobody or apache on UNIX web server systems. When loaded by a web browser, the page should look like Figure 27–15.

image from book
Figure 27–15: Remote IP detection with PHP

The following code is another simple PHP example. It queries another CGI environment variable, HTTP_USER_AGENT, which contains information about the client web browser being used to view the PHP page (this is a primitive example of what is called “browser detection” in web development):

 <html> <head><title>Another Simple PHP Script</title></head> <body> <h2>A Simple PHP Browser Detection Script</h2> Here is your full Web browser profile: <p> <?php    $browser=$_SERVER['HTTP_USER^&GENT'];    print $browser; ?> <hr> <?php if (strpos($browser, 'Firefox') != FALSE) {    ?>       <p>Congratulations on your choice of Firefox.</p>       <?php } else {       ?>       <p>You do not seem to be using <a       href=http : //www.mozilla . com/f iref ox/>Firef ox. </a></p>       <?php } ?> </body> </html>

The interesting thing about this PHP page is what is happening in the PHP if-else structure. The if (strpos($browser, ‘Firefox’) != FALSE) {line shows the strpos statement being used to search for the substring ‘Firefox’ in the variable, $browser, which holds the value of the HTTP_USER_ AGENT environment variable. Also of interest is the way in which raw HTML code can be intermixed with the PHP if-else structure. For instance, <p>Congmtulatiom on your choice of Firefox.</p> is not part of the PHP code (not within the <?php?> delimiting tags), but it will only be displayed on the web page when the if clause evaluates to true. This avoids the need to use print statements to print out HTML tags. When loaded by a web browser, the resulting web page should look like Figure 27–16.

image from book
Figure 27–16: Browser detection with PHP

One of PHP’s most attractive features is its handling of HTML forms. When dealing with HTML forms and PHP, any form element in an HTML page is automatically available to your PHP scripts. The following is an example of a plain HTML form that calls a PHP script, php_form_demo.php, when the Submit button is pressed. The form that is generated is similar to the name and age form shown in Figure 27–14, which was generated by a Python CGI script:

 <html> <head><title>Simple PHP Form Handling Demo</title></head> <body> <form action="php_form_demo.php" method="POST"> Enter your name: <input type="text" name="name" /> Enter your age: <input type="text" name="age" /> < input type ="submit" /> </form> </body> </html>

The php_form_demo.php file must be in the same directory as the preceding HTML document. The contents of php_form_demo.php are

 <html> <body> Your name is <?php echo $_POST["name"]; ?>, and you are <?php echo $_POST["age"]; ?> years old. </body> </html>

When the form’s Name and Age fields are filled out and the Submit button is pressed, the web server loads php_form_demo.php, processes the PHP statements and HTML code in it, and then sends an HTML response back to the client web browser. The resulting web page will contain a single line like this:

 Your name is Joe, and you are 38 years old.

In php_form_demo.php, $_POST is another built-in PHP “autoglobal” array. This array contains all POST method data from the form that called php_form_demo.php. Thus, the $_POST["name”] and $_POST["age”] variables are automatically set for you by PHP

PHP and MySQL

PHP and the MySQL database (http://www.mysql.com/) are often used together to create web applications, particularly as part of the previously mentioned LAMP Web application platform. One of PHP’s most popular features is its ability to interface with and manipulate many free and commercial database management systems, including MySQL, PostgreSQL, Oracle, Sybase, and others. MySQL, an open-source database management system (DBMS), has become a popular choice for use with PHP because of its reputation as a relatively easy-to-use and fast database. MySQL is cross-platform, easily compiled on all UNIX variants, and included as the default DBMS on many Linux distributions. Chapter 16 included instructions for building PHP with its built-in support for MySQL. This section will provide a brief introduction to using PHP’s MySQL support.

To verify that your PHP installation includes MySQL support, you can check the output of the phpinfo() function as described in the section “Apache and LAMP” of Chapter 16 (See Figure 16–5). You should look for a “mysql” section in the phpinfo() output.

You will also need access to a MySQL database on the UNIX web server machine, the machine on which your PHP scripts will be running. If you are not root on the UNIX machine, you will need the system or database administrator to create a MySQL database and grant you sufficient access privileges to that database, typically requiring authentication with your userid and a password that the administrator assigns to you. We will assume that a MySQL database called mytest has been created for you on the web server machine for use with PHP.

After the mytest database has been created, you will need to create a database table containing some fields. We’ll create the table, info, in the mytest database using a PHP script, maketable.php, that will demonstrate how PHP is used to access a MySQL database:

 <?php $user="username"; $password="password"; $database="mytest"; mysql_connect (localhost, $user, $password) ; @mysql_select_db($database) or die( "Unable to select database"); $query="CREATE TABLE info(            id int (6) NOT NULL auto_increment,            firstname varchar(15) NOT NULL,            lastname varchar (15) NOT NULL,            PRIMARY KEY (first),            UNIQUE id (id),            KEY id_2 (id)) "; mysql_query ($query); mysql_close(); ?>

The maketable.php file consists of only PHP statements and no HTML. When you load this file using a web browser, it will display a blank page, but the PHP statements will have been executed silently to create the info table. The $user, $password, and $database variables are used to connect to the mytest MySQL database; you have to substitute your own userid and MySQL password for $user and $password. The $query variable contains the actual MySQL database query that is used to create the info table and its three fields, id, firstname, and lastname. The commands to access the MySQL database begin with the keyword mysql and are fairly intuitive.

You can use another query, shown next, to insert one record into the info table (use this query in the preceding PHP script instead of the CREATE TABLE query and load the PHP script in a web browser):

 $query="INSERT INTO info VALUES ( ",'Bullwinkle','Moose') ".

Here, using the INSERT INTO MySQL query, we are inserting one data record into the info table. The firstname value is ‘Bullwinkle’ and the lastname value is ‘Moose’, but the id value is left NULL (“). This is because we want values for id to be auto-assigned so that each record has a unique id.

Finally, you can display the data you just inserted into the database using the following example script, displaydata.php:

 <?php $username="username"; $password="password"; $database="mytest"; mysql_connect (localhost, $username, $password) ; @mysql_select_db($database) or die( "Unable to select database"); $query="SELECT * FROM info"; $result=mysql_query($query); mysql_close(); print "<b>Database Contents</b><br><br>"; $id=mysql_result($result,0,"id"); $firstname=mysql_result($result,0,"firstname"); $lastname=mysql_result($result,0,"lastname"); print "$id $firstname $lastname"; ?>

Here, the MySQL query we are using is “SELECT * FROM info”, meaning that we are selecting all fields and records (only one record in this example) from the info table. The mysql_result PHP function allows us to easily parse the query result in the $result variable and extract the $id, $firstname, and $lastname. The print command then prints the values of $id, $firstname, and $lastname.




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net