Issue #3 January 2005

LAMP lights the web

Why LAMP tools?

For the entire life of the World Wide Web, the backbone that's kept it upright are the tools of Linux. Linux, Apache, MySQL, PHP, Perl, and Python — collectively known as LAMP — comprise more than two-thirds of the servers, databases, and scripting languages on the web today. It's getting more difficult each day to be a web developer without knowledge and at least a rudimentary level of skill with these tools.

What's the attraction to LAMP tools for developers around the world? In part, it's the open source underpinnings of LAMP tools. They're freely available, easily configured, and very robust. They're in a constant state of development and improvement, adding features suggested by the user community at large. They can be easily deployed, fully configured, and maintained with a minimal amount of effort. In short, the LAMP tool kit allows developers to do what they do best: develop, without spending a disproportionate amount of time in the administrative details.

All these elements are addressed in the package of LAMP tools provided by Red Hat Enterprise Linux. With commerce and the internal communication needs of the enterprise in mind, Enterprise Linux helps to assure that configuring and administering a LAMP server will be as painless a process as is possible.

The tools of LAMP development

The well-defined tools of LAMP web development exist in nearly every Linux distribution. They include:

  • Linux
  • Apache web server
  • MySQL database application
  • PHP scripting language
  • Perl programming language
  • Python programming language

Note that it's not necessary to have all elements of LAMP installed. The LAMP acronym points more to a selection of one the "P" elements (PHP, Perl, and Python) rather than to a need for the inclusion of all of them. Of course, you'll likely find both Perl and Python useful tools for other administrative tasks, so they'll probably be installed on your system whether or not your intent is to use them as an element of LAMP web development.

Enterprise Linux provides the most recent version of each of these packages available at the time of the Enterprise Linux version release. Apache, PHP, Perl, and Python are provided as defaults in the installation of Enterprise Linux, while MySQL requires selection at the time of installation.

Linux

Clearly, the most important element of the LAMP combination is the Linux distribution installed on the server. With dozens of distributions available, the choice can be a bit perplexing. Of the available distributions, however, Enterprise Linux has grabbed the strongest niche in enterprise-grade LAMP web servers for several reasons.

  • Enterprise Linux utilizes the latest stable kernel version.
  • The underlying ext3 file system is a well-proven technology for both rapid recovery and protecting the integrity of the data on the server.
  • The Anaconda-based installation is both easy and accurate, detecting and configuring nearly all the available hardware options for the server.
  • The Anaconda hardware detection routines are particularly well-suited to such devices as SCSI drives and RAID arrays, devices that enhance the overall performance and stability of enterprise-grade servers.
  • Enterprise Linux also provides clean and easy-to-use tools for failover clustering and load balancing services — services that become even more essential in the performance sensitive enterprise environment.

Apache

The second element of LAMP web development is the Apache server, another open source tool with a rich and mature code base. Created in the early 1990s, the HTTP daemon (httpd) package today operates nearly 65% of the web servers worldwide.

Apache is highly configurable and highly modular. A completely customized configuration can be achieved simply by modifying the text configuration file, located on the file system at /etc/httpd/conf/httpd.conf. This file is commented in depth, providing configuration guidance to both the novice and expert webmaster. The code base can also be extended by means of modules, chunks of code that can be loaded at the time the server is started or dynamically, as needed. Hundreds of these modules — most developed by interested third parties — exist in the official Apache code base today.

Apache is part of the default installation of Enterprise Linux. In short, installing Apache doesn't require the further action of selecting it as a package during installation. The Apache package is referred to as httpd in the standard Enterprise Linux configuration. Configuration and related files are named accordingly.

The current version of the Apache software may be downloaded from the Apache website.

MySQL

The third element of the LAMP tool set is the MySQL database, another robust open source tool that has revolutionized the way webpages, graphics, tables, and data sets of all sorts are served up on the web. Web-based databases in general, and MySQL in particular, have made it possible to build and present fully dynamic websites, capable of presenting content in real time. They've also helped to further the goal of separating content from formatting, speeding the load time of sites while making them far more manageable than in the past.

Unlike the Apache server, MySQL is not an element of the default installation in Enterprise Linux. Enterprise Linux does, however, provide the MySQL application in the most recent version as of the time of the Enterprise Linux release. For those who prefer MySQL over the default PostgresSQL database installation in Enterprise Linux, installing the code is simply a matter of selecting it from the databases section during the Enterprise Linux installation.

The MySQL software packages can be downloaded from the MySQL website.

PHP

PHP has, in just a few short years, become one of the predominant scripting languages on the web. It's another integral element of LAMP development,and can be found everywhere from personal homepages to content management systems (such as Drupal) to large-scale corporate intranets. With a relatively easy syntax and open source licensing, webmasters and developers around the world have migrated to PHP from the more difficult and syntactically challenging scripting languages like Perl.

PHP 5.0 was released in July 2004. The newest version fully support object-oriented syntax and provides a command line capability for quick code testing.

PHP is part of the default installation of Enterprise Linux. However, in order to interact properly with a MySQL database, the php_mysql module must be chosen at install time. This module provides the interaction between PHP and MySQL in the form of an Apache module.

The latest version of PHP can be downloaded from the PHP website.

Perl

Perl, the Practical Extraction and Report Language, was the creation of linguist and programmer Larry Wall. Wall had also had a hand in developing the Network News Transfer Protocol (NNTP) to speed delivery of network newsgroup messages to users. In 1987, he released Perl as an "interpreted language optimized for scanning arbitrary text files, extracting information from those text files, and printing reports based on that information."

Perl is an exceptional tool for text parsing. Perl borrowed heavily from other languages such as C, awk, sed, sh, and BASIC, all of which held text processing as their primary focus. In subsequent versions, Perl has added robust database interaction code, unicode support, and object orientation. It's also become much more extensible, supporting thousands of add-on modules via the CPAN (Comprehensive Perl Archive Network) library.

Perl is included in the default installation of Enterprise Linux. The current stable version of Perl is 5.8.6 and can be downloaded in source or binary form from the CPAN site.

Python

The last leg of the LAMP stool is Python, an interpreted scripting language written and released by Guido van Rossum in 1990. van Rossum was, at the time, a huge fan of the British Monty Python television series. The language was originally written for the Amoeba distributed computing system and took on the name of the author's favorite television show.

The easy syntax of Python has made it a great tool for embedding in other languages. This syntax also makes it possible to create and deploy Python applications quickly, with minimal debugging. Like the other languages, Python is also fully extensible, providing the ability to quickly add purpose-specific features simply by adding pre-written modules.

Python is included in the default installation of Enterprise Linux. In fact, the up2date Red Hat Network client in Enterprise Linux is written entirely in Python. No further action is necessary to install Python in a Enterprise Linux system. The current Python version is 2.4 and is available from the Python.org site.

Configuring the LAMP tools

Open source tools have some great advantages over other proprietary tools. Among those advantages is the general ability to configure the tools by editing a text-based configuration file. Nearly any setting can be configured and modified by editing these files. That allows the user to create a configuration that's customized for the particular and unique use of the tool, down to the smallest detail.

Configuring Apache

The text configuration file for the Apache server in Enterprise Linux is located at /etc/httpd/conf/httpd.conf. While the file offers complete customization of all the server parameters, a few are of special interest and importance to new system administrators or webmasters.

Before we look at the important elements of this file, bear in mind that all the configuration parameters in the file are commented, noted with a # symbol prior to the commenting text. These comments are invaluable to anyone configuring the Apache server for the first time. Taking the time to read through the comments for each major section will prove to be a very valuable aid in understanding the inner workings of the Apache server.

LoadModule access_module modules/mod_access.so
LoadModule auth_module modules/mod_auth.so
Example 1. Dynamic Shared Object (DSO) support

As noted earlier, Apache can be configured to load modules dynamically at the time the server is started. Each of the modules that will be loaded is noted in the DSO section of the configuration file. Note that each LoadModule action is appended with both a description of the module and the path to the module, relative to the configuration file. In this example, the mod_access and mod_auth modules are loaded at the time the server is started. Example 1, “Dynamic Shared Object (DSO) support”

User apache
Group apache
Example 2. Server users and groups

As with other files in the Linux system, permissions on the Apache server must be defined. In this case, these permissions are defined in the configuration file. In this example, the user and group in which the server will operate are defined as the apache user and group. This user and group are created on the system when the Apache server is installed. If you prefer to limit access to the server to a particular system user and group, this parameter can be modified accordingly. Example 2, “Server users and groups”

DocumentRoot "/var/www/html"
Example 3. Setting the document root

This configuration parameter defines the location on the file system that will serve as the directory from which all requested documents will be served. For example, the main index.html will reside in /var/www/html/. This parameter, in effect, determines the server document environment; all document requests will be answered with documents residing within this top-level directory. Example 3, “Setting the document root”

Alias /icons/ "/var/www/icons/"
<Directory "/var/www/icons">
    Options Indexes MultiViews
	AllowOverride None
	Order allow,deny
	Allow from all
</Directory>
Example 4. Aliasing directories

Aliasing directories is an important element of the Apache configuration. This allows the use of specific directories in the URL that may or may not be within the DocumentRoot environment of the server. In this example, the URL http://www.example.com/icons/ would open the index.html document in the /var/www/icons/ directory rather than the DocumentRoot directory, /var/www/html/. Aliasing allows an admin or webmaster to use a more concise and intuitive naming scheme or specific locations on the server. Example 4, “Aliasing directories”

Also of importance in this example is the concept of directives. Directives provide specific guidance in handling files on a directory by directory basis. In this example, the directives instruct the server to do such things as allow requests from all addresses (Allow from all) and display an Index where one is available (Options Indexes MultiViews). These directives apply only to the directory enclosed in the <Directory> tags, /var/www/icons/. A complete listing of the Apache directives can be found on the apache.org site.

Configuring MySQL

As with Apache, the configuration for MySQL begins with a simple text file, /etc/my.cnf.

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
     
[mysql.server]
user=mysql
basedir=/var/lib

[safe_mysqld]
err-log=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
Example 5. MySQL configuration file my.cnf

This file defines the startup parameters of MySQL, including the location of the mysqld daemon, the socket the daemon will use for communications, the mysql user, and the base directory in which the the mysql tables will be located. Example 5, “MySQL configuration file my.cnf”

Of all the tools in the LAMP kit, MySQL has the most concise configuration file. What you see in Example 5 is really all there is in the default configuration. More variables can be added to this configuration, but they're beyond the scope of this article.

Configuring PHP

Of all the configuration options in the LAMP setup, PHP has perhaps the most detailed configuration file. /etc/php.ini defines all the working parameters of the PHP installation and includes a clear and concise set of comments. These comments, as with the httpd.conf file, provide valuable insight into the operation of PHP on the system. What follows are some of the more important elements of the /etc/php.ini file. the section called “Configuring PHP”


;
; Safe Mode
;
safe_mode = Off

Example 6. Safe mode configuration

Safe mode in PHP provides some additional security checks, such as checking the user and group IDs when opening files. Additionally, PHP restricts the execution of files by limiting the directories from which it will execute files. Finally, safe mode restricts the system from passing environment variables by limiting those environment variables that can be changed to a list defined in the /etc/php.ini file. The configuration setting for safe mode is a simple On or Off value. Example 6, “Safe mode configuration”


;;;;;;;;;;;;;;;;;;;
; Resource Limits ;
;;;;;;;;;;;;;;;;;;;
                                                                                                                            
max_execution_time = 30		;Maximum execution time of each script, in seconds
max_input_time = 60		;Maximum amount of time each script may spend parsing request data
memory_limit = 8		;Maximum amount of memory a script may consume (MB)

Example 7. Resource limits

The resource limits configuration in PHP defines the time and memory limits for the execution of scripts. This is especially important on large systems with high traffic loads.

The resource limits section also provides a good example of the commenting style of the /etc/php.ini file. Comments are denoted with a semicolon, with banner comments beginning each section and inline comments describing the function of each configuration option. Example 7, “Resource limits”

error_reporting = E_ALL
Example 8. Error reporting

PHP will report a full range of errors, either via logging or in the display. It's become a more widely accepted practice to provide reporting on all errors (E_ALL) for the purposes of logging only. Reporting errors in the display can present security concerns, as a skillful cracker can often determine the state of the system by the error messages reported in the browser window. The error_reporting = E_ALL configuration option sends these error messages to the log file defined elsewhere in the configuration. Example 8, “Error reporting”


display_errors = Off

Example 9. Displaying errors

Thus, displaying errors in the browser should be turned off, as shown in Example 9, “Displaying errors”.

register_globals = Off
Example 10. Register globals

Registering globals in PHP will allow variables declared in one page to be passed unaltered to another. For versions of PHP through 3.0, this was the default behavior. However, several security exploits have been discovered that leverage registered globals in PHP. The default configuration is now to turn off the register_globals, forcing users to turn them on only if necessary. Example 10, “Register globals”


max_post_size = 8M

Example 11. Max post size

PHP works extensively with the GET and POST variables found in HTML forms. The max_post_size configuration limits the amount of data that can be sent to another page via the POST method. In this example — the default — no more than 8 MB of data can be sent with the POST method. Example 11, “Max post size”


magic_quotes_gpc = Off

Example 12. Magic quotes

The magic quotes configuration determines whether or not an escape character, such as /, will be required to escape quotes in a script. Turning magic quotes on will remove the requirement for the escape character. The default configuration in PHP is to turn off the magic quotes capabilities, requiring that quotes be escaped in all scripts. Example 12, “Magic quotes”

These are a few of the important elements of the /etc/php.ini configuration file. A full explanation of all variables in the file can be found in the inline comments, or on the PHP website.

Configuring Perl

By itself, Perl doesn't utilize a global configuration file. Instead, your primary configuration interaction with Perl will be in the /etc/httpd/conf.d/perl.conf file on a Enterprise Linux system. This file directs and controls the interaction of Perl with the Apache server via the mod_perl Apache module.

LoadModule perl_module modules/mod_perl.so
Example 13. Loading the mod_perl module

This line in /etc/httpd/conf.d/perl.conf is responsible for loading the mod_perl.so module at the time the Apache server starts. Example 13, “Loading the mod_perl module”


PerlWarn On

Example 14. Enabling Perl warnings

This option directs Perl to write all warnings to the server error log. By default, this option is turned off. It's useful to turn on during testing. However, it does affect the server performance, so it's a good idea to turn it off on a production server. Example 14, “Enabling Perl warnings”

The /etc/httpd/conf.d/perl.conf file also contains server directory specific configuration, in the Apache directive format. These options are turned off by default but commented liberally should you choose to use them.

Configuring Python

As Python has some basis in Perl, it should come as no surprise that the configuration for Python is almost identical to that of Perl. Rather than providing a global Python configuration file, configuration is related to the interaction with the Apache server. Like its counterpart in Perl, this file is located at /etc/httpd/conf.d/python.conf.


LoadModule python_module modules/mod_python.so

Example 15. Loading the Python module

The similarities between Python and Perl configurations are clear. If you've looked closely at the Apache configuration file /etc/httpd/conf/httpd.conf, you've also noticed that this syntax exactly reflects that of the LoadModule configuration in httpd.conf. You'll find that this is a common practice among scripting languages requiring the loading of an Apache module. Example 15, “Loading the Python module”

Also consistent with Perl is the use of Apache directives in python.conf. Like Perl, these are commented out, or shut down, by default but can be uncommented as necessary. Additional directives related to Python can be added as well.

LAMP examples

As you'll see in the following examples, the LAMP tools are easy to implement and, in nearly every way, compliment each other completely. These are simple examples, intended only to show the ease with which LAMP tools can accomplish many tasks.

Use the following examples to get a feel for the code and the syntax of each language. A thorough explanation of the code is beyond the scope of this article. In fact, hundreds of books have been written about each of these scripting languages. The examples are intended only to give you a feel for the syntax and flow of each language, pointing out some interesting web-related pieces along the way.

PHP examples

One of the strengths of PHP is the ability to connect to MySQL with ease. The first example, PHP Page Statistics, shows off this capability by utilizing a MySQL database to track hits to a webpage — which, of course, is on an Apache server. Example 16, “PHP page statistics”


<?php
/* connect to the database 
$link = mysql_connect('localhost','logger','');
mysql_select_db('php',$link);

/* populate a variable with the db query
$qs = "UPDATE pagestats SET hits=hits+1 WHERE uri = '$SCRIPT_FILENAME'";

/* query the db
$r =  mysql_query($qs,$link);

/* check the number of affected db rows and, if necessary, insert into db
if (mysql_affected_rows($link) < 1) {
    mysql_query("INSERT INTO pagestats VALUES ('$SCRIPT_FILENAME',1,SYSDATE())",
	$link);
}

/* another query
$res = mysql_query("SELECT hits, UNIX_TIMESTAMP(since) as since FROM
pagestats
WHERE uri = '$SCRIPT_FILENAME'",$link);

/* assign the results of $res to $sincesecs
$sincesecs = mysql_result($res,0,'since');
$modsecs = filectime($SCRIPT_FILENAME);

$hits    = mysql_result($res,0,'hits') + 1;

/* format the date
$dateformat = 'l F d, Y h:i:s A';

$since   = date($dateformat,$sincesecs);
$lastmod = date($dateformat,$modsecs);
?>

Example 16. PHP page statistics

<html> 
<head>
</head>
<body> 
<h1>Checking a Database Query ...</h1>
<?
	$dbcon=mysql_connect("db.fullbrain.com","cortex")
		or exit("<p><font color=red>Couldn't connect to database</font></p>");
	mysql_select_db("mydatabase");
	$sql="SELECT * FROM geography WHERE feature = '" . $place ."'";
	$result = mysql_query($sql);
	$nrows = mysql_num_rows($result);
	if($nrows != 0)
	{
		print "<p>Data for " . $place;
		print "<table border=2><tr><th>Latitude<th>Longitude<th>East<th>North\n";
		for($j=0;$j<$nrows;$j++)
		{
			$row = mysql_fetch_array($result);
			print "<tr><td>" . $row["latitude"];
			print "<td>" . $row["longitude"];
			print "<td>" . $row["east"];
			print "<td>" . $row["north"];
			print "\n";
		}
		print "</table>\n";
	} else {
		print "<p>No Entry for " . $place;
	}
	mysql_close($dbcon);
?>
</p>
</body>
</html>

Example 17. PHP/HTML hide-and-seek and error reporting

Example 17 demonstrates two useful features of PHP. The first is the ability to mix it up with HTML, jumping between HTML and PHP using the <?php and ?> delimiters. The example also writes HTML directly using the print statements. Example 17, “PHP/HTML hide-and-seek and error reporting”

The second item of interest is the way PHP handles errors, especially in the MySQL database. In this example, a SQL statement is appended with or exit followed by an error message to send to the browser in HTML. This could also be written using the or die syntax. In any event, these types of error messages shouldn't be necessary in a production page, as thorough debugging prior to rolling to production should eliminate most of these types of errors.

Perl examples

Like PHP, Perl is an outstanding tool for the web. It has been the chosen scripting language for the Common Gateway Interface or CGI. Also like PHP, Perl is capable of generating webpages on the fly, as shown in Example 18, “Using Perl to generate HTML”. Note that Perl makes use of the print statement to create the HTML in the browser.


#!/usr/local/bin/perl
#
#

if ($#ARGV != 1) {
    print "usage: htmlslides base num\n";
    exit;
}

$base = $ARGV[0];
$num = $ARGV[1];

for ($i=1; $i <= $num; $i++) {

    open(HTML, ">$base$i.html");

    if($i==$num) {
	$next = 1;
    } else {
	$next = $i+1;
    }

    print HTML "<html>\n<head>\n<title>$base$i</title>\n</head>\n<body>\n";
    print HTML "<a href=\"$base$next.html\"><img src=\"$base$i.jpg\"></a>\n";
    print HTML "</body>\n</html>\n";

    close(HTML);
}

Example 18. Using Perl to generate HTML

Python examples

As noted earlier, the syntax of Python is much more loose than that of the other LAMP languages. Example 19, in contrast to those of PHP and Perl, looks very clean. Notice the lack of braces ({}) and brackets ([]). The Python syntax is, in fact, white-space-sensitive; it uses white space rather than the typical braces or brackets to break out the code.

Python is also renowned for the ease with which it can be learned. In many ways, Python is a great choice if you've had no previous programming experience. Further, the concepts of Python carry through to the other languages.

In Example 19, “Python page hits”, Python monitors a log and registers each time the page is hit.


#!/usr/bin/env python

# usage: ./log_watch.py [logfile]

import sys, time
from weblog import combined

file = open(sys.argv[1])
log = combined.Parser(file)
while 1:
	while log.getlogent():
		print "host: %s\n page: %s" % (log.client, log.url)
	file.seek(0, 1)
	time.sleep(5)

Example 19., Python page hits

There are some clear differences in the coding languages used in LAMP web development. Syntax, structure, and conventions all make for an interesting combination and a selection that will surely meet your needs and coding style. Combined with the power, extensibility and freely available support of Apache and MySQL, LAMP tools have become the real hammer and nail of the web.

Further Reading

  • Apache.org — The Apache website. Contains download links, full documentation, installation instructions, and related background material regarding the Apache Foundation.
  • PHP.net — The PHP website. Contains documentation, download links and thousands of working examples of PHP code.
  • MySQL.com — The MySQL website. Contains documentation and download links for the MySQL database.
  • Perl.org — The official Perl website. Contains documentation, download links and a history of Perl and the Perl community.
  • Python.org — The official Python website. Contains documentation and download links for Python.
  • Red Hat Enterprise Linux — Full documentation for Red Hat Enterprise Linux, including setup, reference and security guides, developers handbooks, and an introduction to system administration.

About the Author

Tony Steidler-Dennison is a PHP/MySQL developer and Linux systems engineer. He designs and configures passenger-cabin file servers for commercial aviation. He's the co-author of Professional Red Hat Enterprise Linux 3 and author of the upcoming Build Your Own Web Server With Linux and Apache. He also maintains the tech blog, The CodeMode Chronicles.