 |
 |
 |
 |
|
|
|
|
|
|
LAMP is a popular web-development
buzzword. It stands for Linux, Apache,
MySQL, and PHP. (The P can also stand
for Perl or Python, but this article
focuses on PHP.) These open source
tools provide you with a world-class
platform for web applications. Running
on the Linux operating system, the
Apache web server, MySQL database,
and PHP programming language gives
you everything you need to build sturdy,
secure, and speedy dynamic websites.
This article takes you through the
basics of installing Linux, Apache,
MySQL, and PHP so that you can get
up and running in no time. |
| |
Installing
Linux
Your first step in installing Linux is to pick a
distribution. Various companies produce different
distributions, which are collections of the core
operating system bundled with assorted supporting
software and packed with a helpful installer. Some
of the most popular distributions are Red
Hat Linux, SuSE
Linux, and Debian
Linux. |
| |
| The distributions
differ in how their installers work, how you maintain
add-on packages, what software is included with
them, and how much technical support you can get.
Each distribution is downloadable for free, but
if you purchase a branded version from a particular
company, you can get technical support, extra software,
and other goodies. |
| |
| In this article, I'm
going to mostly talk about Debian Linux, since it's
non-commercial and easy to install and maintain.
Apache, MySQL, and PHP work equally well on any
Linux distribution. The main difference you'll have
to look out for—if you're using a different
distribution—is how you install binary packages
of Apache, MySQL, or PHP. |
| |
| To get Debian Linux,
visit Debian's
Distribution page. |
| |
| The easiest way to
install Debian is to buy a set of CDs. These can
be very inexpensive ($5) and there are vendors all
over the world. Visit the Vendors
of Debian CDs page to find a third-party distributor. |
| |
| If you can't wait
for CDs to arrive in the mail, you can download
a set of installation files, and put those on a
CD or on floppy disks. Boot from the CD (or the
first floppy) and the installation system will retrieve
the rest of what it needs from the Internet. This
is called a "Network install". You can
find CD images for a network install on Debian's
Network Installation page. If you prefer to
work with floppy disks, you can find links to floppy
images for a network install on Debian's
Floppy Disk Installation page. |
| |
| A network install
requires that your computer is connected to the
Internet during the entire installation procedure.
Fast (DSL, Cable Modem, or above) network access
is not mandatory for a network install, but is a
practical requirement. You'll need to download a
few hundred megabytes of data. Ordering CDs by overnight
shipping will probably get you what you need quicker
than downloading that much over a regular modem.
|
| |
| If you want to make
all the Debian installation disks yourself, you
can use a utility called jigdo (which is short for
"Jigsaw Download"). Instead of downloading
huge image files for each disk, jigdo downloads
the individual package files that make up each disk
and then stitches them together into a disk image.
Learn more about using jigdo on Debian's
jigdo page. |
| |
| To summarize, the
easiest (and cheapest, if you value your time at
more than a few dollars an hour) way to get up and
running with Debian Linux is to buy a set of CDs.
Boot off of the first CD, and the menu-driven installer
will take you through all the steps required to
install Debian Linux on your computer. |
| |
Installing
Apache
Apache is the most popular web server in the world.
It's fast, stable, and free. There are two major
releases of Apache available: Apache 1 and Apache
2. While Apache 2 offers some great new features,
this article focuses on Apache 1. Apache 1 is more
widely used and works with more third-party software.
You can read general information about Apache by
visiting the Apache
Server FAQ. |
| |
| The easiest way to
install Apache involves using binary packages specific
to your Linux distribution. |
| |
- On Debian Linux, use the
apt-get
utility to install the apache package:
# apt-get install apache
- On distributions using RPM packages (such
as Red Hat Linux), visit the RPM
Resource Page and use rpmfind.net to locate
and download an appropriate Apache package.
Then, install it with the
rpm
program:
# rpm --install apache-1.3.27-2.i386.rpm
- The system generally requires that you install
packages with
apt-get
or rpm as
the root user. To change to root, type:
% su -
- At the Password: prompt, enter the root password
that you set up when installing Linux. In this
article, the command prompt for lines that should
be executed as root is # and
the prompt for lines that should be executed
as a regular user is %.
|
| |
| If you can't (or don't
want to) use a package file, you can compile Apache
from its source code. This requires that you have
a C compiler and the associated development tools
installed. |
| |
- Select an Apache download mirror by visiting
the Apache
HTTP Server Project.
- Scroll to the bottom of the page to find a
"Unix Source" link for a version of
Apache 1. As of this writing, the current version
of Apache 1 is Apache 1.3.27 and the file to
download is apache_1.3.27.tar.gz.
- After you've downloaded the file, uncompress
it and extract all of the individual files in
the archive with:
% gunzip < apache_1.3.27.tar.gz
| tar xvf -
- Then, change into the directory where the
extracted files are:
% cd apache_1.3.27
- Next, you need to configure Apache's compilation
settings with the configure script. There are
a number of different options you can pass to
configure. Get a look at them all with the
--help
option:
% ./configure --help
- Don't forget the ./ before
configure. That runs the copy of the configure
program in the Apache directory. One option
you need to specify to configure is
--enable-module=so.
This configures Apache to be able to dynamically
load modules without recompiling. It's easiest
to use PHP as a dynamically loaded module, so
this Apache functionality is important. So,
at the bare minimum, you want to run:
% ./configure --enable-module=so
-
By default, Apache and its
configuration files are installed in the /usr/local/apache
directory. You can change this with the --prefix
option to configure the location. For example,
you can install everything under /opt/apache
:
% ./configure --enable-module=so
--prefix=/opt/apache
- You can also change the directories into which
Apache is installed by using the
--with-layout
option. The config.layout
file in the Apache distribution describes various
directory configurations for where Apache files
are installed. GNU is one of the layout configurations
mentioned in config.layout. Select one of them
like this:
% ./configure --enable-module=so
--with-layout=GNU
-
After successful configuration,
run make
to compile Apache's source code:
% make
- Then, install Apache with
make
install:
% su -
# make install
Note: The
make install command needs to be run as root
, so the su -
command changes your permissions to those of
the root user.
|
| |
| If you've set up Apache
using binary packages, then it's automatically set
to start up each time your system starts up. If
you've built Apache yourself, you need to take some
extra steps to set up Apache to start on system
startup. The steps below must be performed while
your permissions are set as the root user: |
| |
-
On Debian Linux, type the
following:
# cp /usr/local/apache/bin/apachectl
/etc/init.d/apache
# update-rc.d apache defaults
- If you've used the
--prefix
or --with-layout
configuration options for Apache, then substitute
the appropriate directory for apachectl.
|
| |
Installing
MySQL
MySQL is a fast, robust database server packed
with functions. If possible, install MySQL using
binary packages for your distribution. |
| |
- On Debian Linux, type the following:
# apt-get install mysql-server
- For other Linux distributions, you can find
RPMs and regular binary distributions on the
MySQL
3.23 Downloads page.
- As mentioned previously, you must set your
permission as the root user when you perform
these steps. If you download a binary distribution,
uncompress it and extract files from the archive
like this:
# cd /usr/local
# gunzip < /tmp/mysql-3.23.55-pc-linux-i686.tar.gz
| tar xvf -
# ln -s mysql-3.23.55-pc-linux-i686 mysql
Note: The above assumes that
you've downloaded the MySQL binary distribution
into the /tmp directory. It extracts the files
into /usr/local/mysql-3.23.55-pc-linux-i686
directory, and then creates a symbolic link
so that /usr/local/mysql points to the MySQL
directory.
- Follow the instructions in the INSTALL-BINARY
file in the MySQL distribution for installing:
# groupadd mysql
# useradd -g mysql mysql
# cd mysql
# scripts/mysql_install_db
# chown -R root .
# chown -R mysql data
# chgrp -R mysql .
-
The groupadd
and useradd
commands are used to create a specific user
and a group, which MySQL will use when it's
running. It's good practice to run servers
as their own users—otherwise the server
usually runs as root, which can cause security
problems. Apache automatically runs as the
user nobody, so you don't need to do anything
special to prevent it from running as root.
The scripts/mysql_install_db
program creates some initial tables that MySQL
needs to start up. The chown
and chgrp
commands set the permissions correctly on
the MySQL files.
|
| |
| Now we're ready to
start MySQL. |
| |
- Enter the following:
# bin/safe_mysqld --user=mysql
&
- MySQL maintains its own set of users and passwords
to control access to data in its databases.
These users and passwords are separate from
the users and passwords that control access
to your Linux server itself. When first installed,
MySQL has one user, root , with no password.
So the very first thing you should do after
installing MySQL is to set a password for that
user. Use the
mysqladmin
command for that:
% mysqladmin -u root password
'new-password'
- Substitute what you want the password to be
for new-password in the text above. If you installed
MySQL with
apt-get,
then mysqladmin
is in your path so you can just type mysqladmin
to run it. If you installed the binary distribution
into /usr/local, then you need to type the full
pathname to mysqladmin:
% /usr/local/mysql/bin/mysqladmin
-u root password 'new-password'
- After setting the password for the root user,
you should create a database and a user that
can access that database. You'll use that database
and user when connecting from PHP.
% mysqladmin -u root -p
create mydb
-
This command creates a database
called mydb. At the "Password:"
prompt, enter your new password. You can use
any name for the database that you'd like,
as long as it's made up of just letters, numbers,
and the underscore symbol ( _).
- To create a user, run the MySQL console tool
as the root user:
% mysql -u root -pNewPassword
At the "Password:" prompt, enter your
new password.
- Then issue the following command:
Note: Don't type the mysql>
part. That's just the prompt that the MySQL
console tool uses.
mysql>
GRANT ALL PRIVILEGES ON mydb.* TO myuser@localhost
IDENTIFIED BY 'mypassword';
This command says that the user myuser
can do anything it wants to any table in the
mydb database, but that myuser
has to log in with the password mypassword
from the same host that is running the database.
The localhost
is a special hostname. When a program tries
to connect to localhost, it connects to the
same host that the program is running on.
-
If you installed the binary
distribution but want MySQL to start up when
the server does, you need to set this manually.
This is similar to the auto-start setting
we made for Apache:
# cp /usr/local/mysql/support-files/mysql.server
/etc/init.d/mysql
# update-rc.d mysql defaults
|
| |
Installing
PHP
Now that Linux, Apache, and MySQL are installed,
you can install PHP. It is critical that you install
these in the order described in this tutorial. Although
there are Debian packages available for PHP, they
provide an outdated version of PHP. Therefore, the
instructions here outline how to download the source
for PHP and build it yourself. |
| |
- Go to the PHP
downloads page. Click the link under "Complete
Source Code" at the top of the page to
download the tar.gz (not the
tar.bz2 ) version of the file. You'll be directed
to a page where you can download the actual
file from a mirror closest to you.
- After you've downloaded the file, uncompress
it and extract all of the individual files in
the archive with this command:
% gunzip < php-4.3.0.tar.gz
| tar xvf -
- Then, change into the directory where the
extracted files are:
% cd php-4.3.0
- Like Apache, you need to configure the compilation
settings in PHP with the configure script. You
can see all the configuration options with the
--help script:
% ./configure --help
- To compile successfully as an Apache module,
PHP needs a tool from Apache called the
apxs
utility. If you compiled Apache from source,
then you already have the apxs
utility. If you installed Apache with apt-get,
then you need to install another package, apache-dev,
to provide apxs to PHP:
# apt-get install apache-dev
- To configure PHP to work with Apache, you
need to use the
--with-apxs
option. Additionally, PHP needs to be told to
include MySQL support:
% ./configure --with-apxs
--with-mysql
- PHP has lots of other modules that can parse
XML, encrypt, and decrypt data, generate graphics
or PDF files, and all sorts of other wonders.
To enable these other modules, include the appropriate
options to configure. Some modules require external
libraries to be installed. You can use Debian's
dselect tool
to find and install the packages that contain
these additional libraries.
After configure runs, type make
to compile PHP:
% make
- Then, while you are logged in as root, type
make install
to install PHP:
# make install
- The
make install
script in PHP does a number of things. Aside
from copying the PHP Apache module to the right
directory, it also installs a command-line ("CLI")
PHP binary in this directory: /usr/local/bin/php.
Additionally, it installs some of the PEAR library
in this directory: /usr/local/lib/php. PEAR
is the PHP Extension and Application Repository,
a collection of high quality reusable PHP components.
- After PHP is installed, you still need to
edit the Apache configuration file to tell it
which files should be parsed by PHP. If you've
installed the Debian Apache package, Apache's
configuration file, httpd.conf,
is located here: /etc/apache/httpd.conf . If
you've built Apache from the source, then the
location of httpd.conf varies.
If you specified a prefix of /usr/local/apache
when configuring Apache, then the file is located
here: /usr/local/apache/conf/httpd.conf.
Once you've located the httpd.conf
file, find this line:
#AddType application/x-httpd-php
.php
Note: If you installed Apache
using the Debian packages, this line will automatically
exist in the httpd.conf file. If you installed
Apache from the source, then you'll need to
add this line into the httpd.conf file manually.
- Remove the # at the beginning
of the line and save the file. This change notifies
Apache to make the PHP engine parse all files
that end with the extension .php.
- Now restart Apache to have the new PHP-aware
configuration take effect, by typing the following:
# apachectl restart
|
| |
Testing PHP
Now that we've installed PHP, we're ready to test
the configuration. |
| |
- First, create a file in your web server document
root called info.php. Add the
following line:
<?php phpinfo(); ?>
-
Your web server document root
is the directory after the DocumentRoot directive
in the Apache httpd.conf file.
For example, if httpd.conf
contains the line:
DocumentRoot /var/www
Then you should create info.php in this location:
/var/www/info.php. Bring up the page with
the lynx
script:
% lynx http://localhost/info.php
- You should see a screen of information about
your PHP configuration. If you don't see anything,
press \ in Lynx to view the
document source. If the document source contains
the PHP source code
(<?php
phpinfo(); ?> ), then Apache
hasn't been configured properly to hand off
.php pages to the PHP engine. If this occurs,
make sure you uncommented the proper AddType
line in httpd.conf and successfully
restarted the server.
If you get an error message stating that info.php
was not found, make sure you created the file
in the correct DocumentRoot directory. Also,
be sure that you performed the "save file"
command in your editor, to ensure that you actually
saved the file to disk.
|
| |
Using PHP
Now that you've got PHP set up and working properly,
the fun begins. Here's a simple page that displays
a feedback form and sends an e-mail message back
to you with the results: |
| |
<?php
$to_addr = 'webmaster@example.com';
if (isset($_REQUEST['submit'])) {
$mail_body = 'Name: '.$_REQUEST['name'];
$mail_body .= "\nEmail: ".$_REQUEST['email'];
$mail_body .= "\nMessage:
".$_REQUEST['message'];
mail($to_addr,'Form Feedback',$mail_body);
print "Thank you for the
feedback.";
} else {
print<<<_HTML_
<form method="POST" action="$_SERVER[PHP_SELF]">
<table>
<tr><td>Name:</td><td><input
type="text" name="name"></td></tr>
<tr><td>Email:</td><td><input
type="text" name="email"></td></tr>
<tr><td>Message:</td><td><textarea
name="message"></textarea></td></tr>
<tr><td colspan="2"><input
name="submit" type="submit"></td></tr>
</form>
_HTML_;
}
?> |
| |
PHP automatically
stores variables from forms in the $_REQUEST
array. If $_REQUEST['submit']
is set, that means that the form has been submitted,
so the script formats a message in the variable
$mail_body and
uses the mail()
function to send the message to the address stored
in the variable $to_addr.
If $_REQUEST['submit']
isn't set, the script prints out the HTML for the
form instead. Inside the <form> tag, the action
of the script is set to the special variable $_SERVER[PHP_SELF],
which is the path of the current page. This causes
the form to submit to itself, a common and helpful
technique that lets you put the logic to process
a form in the same file with the HTML to display
the form. |
| |
Using PHP
and MySQL
It's easy to use PHP and MySQL together to store
and retrieve information. Instead of the feedback
form sending e-mail messages, it can store the messages
in a table for later viewing. Follow the steps below
to exchange data with a MySQL database using PHP:
|
| |
- First, create a table to hold the messages.
Run the
mysql
command-line utility with the database, username,
and password you created earlier:
% mysql mydb -umyuser -pmypassword
- Then, at the mysql> prompt, type the following
SQL code to create a table:
CREATE TABLE messages
(
id int unsigned not null auto_increment
primary key,
name varchar(255),
email varchar(255),
message mediumtext
);
- This creates a table with four columns:
- id: a numerical index that will be unique
for each message
- name: a text field to hold the submitted
name
- email: a text field to hold the submitted
email address
- message: a larger text field for the message
body
- Next, the feedback form page needs to be modified
to save the information in the database instead
of sending an e-mail message. Here's the new
version:
<?php
if (isset($_REQUEST['submit'])) {
mysql_connect('localhost','myuser','mypassword');
mysql_select_db('mydb');
mysql_query("INSERT INTO
messages (name,email,message) VALUES ('"
.
$_REQUEST['name']
."','" . $_REQUEST['email'] . "','"
.
$_REQUEST['message']
. "')");
print "Thank you for the
feedback.";
} else {
print<<<_HTML_
<form method="POST" action="$_SERVER[PHP_SELF]">
<table>
<tr><td>Name:</td><td><input
type="text" name="name"></td></tr>
<tr><td>Email:</td><td><input
type="text" name="email"></td></tr>
<tr><td>Message:</td><td><textarea
name="message"></textarea></td></tr>
<tr><td colspan="2"><input
name="submit" type="submit"></td></tr>
</form>
_HTML_;
}
?>
- The code for printing the form is the same,
but instead of constructing an e-mail message,
this program connects to MySQL with
mysql_connect(),
selects a database with mysql_select_db(),
and issues a query with mysql_query().
The three arguments to mysql_connect()
are the host to connect to and the username
and password to connect with. The argument to
mysql_select_db()represents
the database to use. These are the database,
user, and password you created earlier with
mysqladmin
and the GRANT
command.
In practice, you should always check if each
of these MySQL functions returns an error or
not, but that error checking has been left out
of this example, for simplicity.
- You can use the same MySQL functions to create
a companion page to print out all the feedback
in the messages table:
<?php
mysql_connect('localhost','myuser','mypassword');
mysql_select_db('mydb');
$r = mysql_query('SELECT * FROM messages');
if (mysql_num_rows($r)) {
print '<table border="1">';
print '<tr><th>Name</th><th>Email</th><th>Message</th></tr>';
while ($ar = mysql_fetch_array($r,MYSQL_ASSOC))
{
$name = htmlspecialchars(strip_tags($ar['name']));
$email = htmlspecialchars(strip_tags($ar['email']));
$message = htmlspecialchars(strip_tags($ar['message']));
print "<tr><td>$name</td><td>$email</td><td>$message</td></tr>\n";
}
} else {
print 'No messages.';
}
?>
- The same functions are used to connect to
the database and issue a query. This time, however,
instead of an
INSERT
query to put data into the table, the script
uses a SELECT
query to retrieve all the data in the messages
table. If there are rows to display, a table
header is printed out. Then, mysql_fetch_array()
retrieves each row into an associative array,
one at a time. Each value to be printed is processed
with strip_tags()
to remove HTML tags and htmlspecialchars()
to turn HTML entities (like &) into their
entity-encoded equivalents (like & ).
Using strip_tags()
and htmlspecialchars()
is important to protect against cross-site scripting
attacks.
|
| |
Writing PHP
in Dreamweaver MX
Dreamweaver MX includes support for PHP and MySQL.
PHP documents are in the "Dynamic Page"
category of the File > New dialog box. You can
type PHP directly into the file, or you can use
the PHP tab on the Insert panel to get access to
some handy PHP shortcuts. Dreamweaver MX also offers
some auto-completion, so if you type $_
a list pops up with the name of the superglobal
arrays (such as $_REQUEST,$_GET,
$_POST, etc.)
You can use the arrow keys and the Return key to
pick a choice from the pop-up list, or just keep
typing and ignore it. Dreamweaver MX also has PHP-aware
syntax coloring, so function names are blue, language
constructs like if and else are green, and so on.
|
| |
| The PHP and MySQL
integration in Dreamweaver MX really shines, though,
when you want to display and manipulate dynamic
data. First, create a "Site" to hold your
files. When creating the site, be sure to specify
that you want to use the "PHP MySQL" server
technology. The server in your new site can be your
new Linux server set up as described in this article
or any other server you have access to that's running
PHP and MySQL. Read the "Setting up a Dreamweaver
site" section of the Dreamweaver help file
for more details about defining a site. |
| |
- Once your site is set up, create a new file
in the site by selecting "Site" in
the Site tab of the Files panel and pressing
Ctrl+Shift+N.
Rename your new file from untitled.php
to something meaningful. Double-click the filename
to open your new file.
- Now it's time to set up a database connection.
Click the "Databases" tab of the Application
panel and then the button with the "+"
on it.
In the MySQL Connection dialog box that pops
up, fill in the text boxes with the appropriate
information. Your database server's host name
(localhost in our examples above) is entered
in the "MySQL Server" box. The user
name and password ( myuser and mypassword )
is entered in the User Name and Password boxes.
The database name ( mydb ) is entered in the
"Database" box.
|
| |
 |
| |
It's OK to use localhost as the host name because
the code to connect to the database runs on
your server, not on the desktop computer that
you're using to run Dreamweaver. Click the "Test"
button in the dialog box to make sure that the
information you've entered works correctly.
- After you've created a database connection,
you can use that connection to easily populate
pages with dynamic data. To create a page that
displays all the records in the messages table
we used above, we first need to create a Recordset.
A Recordset is a collection of data that results
from a database query. To create a Recordset,
go to the "Server Behaviors" tab of
the Applications panel and click on the button
with the "+" on it.
From the list of choices that appears, pick
Recordset.
|
| |
 |
| |
- In the Recordset dialog box that appears,
enter a name for the new Recordset, such as
"Messages". Select the database connection
you created from the Connection drop-down box
and the messages table from the Table drop-down
box.
The Columns, Filter, and Sort sections of the
dialog box let you select which columns from
the table to display and how they should be
sorted. For this example, let's just display
the name,
email, and
message columns.
First, click the "Selected" radio
button and then select name,
email, and
message from
the column list.
To sort the messages in ascending alphabetical
order by name, choose name
and Ascending
in the Sort drop-downs. When you click the "OK"
button in the Recordset dialog box, your PHP
code is inserted into your new file to access
the data in the database.
- Once the Recordset is created, you can display
information from it. Position the cursor just
after the <body> tag in your new file.
Then, select "Dynamic table" from
the "Insert > Application Objects"
sub-menu. In the dialog box that appears, choose
your newly created Recordset from the Recordset
drop-down box and click the "All Records"
radio button.
|
| |
 |
| |
When you click OK,
Dreamweaver inserts HTML and PHP into your file
to loop through each row in the Recordset and print
the results in a table. You can see the results
by previewing the page in a browser (press F12 or
use the "File > Preview in Browser"
sub-menu).
The "Adding Dynamic Content to Web Pages"
section of the Dreamweaver online help has more
details about the other Application Objects and
how you can use them to easily populate your pages
with information from a database. You can also look
on the Macromedia
Dreamweaver Exchange for more information about
Server Behaviors and Application Objects. |
| |
| |
|
| About
the author
David Sklar is the co-author of the PHP
Cookbook, published by O'Reilly &
Associates, an independent technology consultant
in New York City, and an instructor at the New
School. He was a founder and the Chief Technology
Officer of both Student.Com and TVGrid.Com, where
he led teams of PHP developers that built multilingual
data-driven web applications. He holds a degree
in Computer Science from Yale University.
|
|
Submit feedback
on our tutorials, articles, and sample applications.
|
| |
|
|
|