Tutorial Con Web Server
Tutorial Con Web Server
Introduction
A “LAMP” stack is a group of open source software that is typically installed
together in order to enable a server to host dynamic websites and web apps
written in PHP. This term is an acronym which represents the Linux operating
system with the Apache web server. The site data is stored in a MySQL
database, and dynamic content is processed by PHP.
Prerequisites
In order to complete this tutorial, you will need to have an Ubuntu 22.04 server
with a non-root sudo-enabled user account and a basic firewall. This can be
configured using our initial server setup guide for Ubuntu 22.04.
Start by updating the package manager cache. If this is the first time you’re
using sudo within this session, you’ll be prompted to provide your user’s
password to confirm you have the right privileges to manage system
packages with apt:
Once the installation is finished, you’ll need to adjust your firewall settings to
allow HTTP traffic. Ubuntu’s default firewall configuration tool is called
Uncomplicated Firewall (UFW). It has different application profiles that you
can leverage. To list all currently available UFW application profiles, execute
this command:
Output
Available applications:
Apache
Apache Full
Apache Secure
OpenSSH
Output
Status: active
To Action From
-- ------ ----
OpenSSH ALLOW Anywhere
Apache ALLOW Anywhere
OpenSSH (v6) ALLOW Anywhere (v6)
Apache (v6) ALLOW Anywhere (v6)
You can do a spot check right away to verify that everything went as planned
by visiting your server’s public IP address in your web browser (view the note
under the next heading to find out what your public IP address is if you do not
have this information already):
http://your_server_ip
The default Ubuntu 22.04 Apache web page is there for informational and
testing purposes. Below is an example of the Apache default web page:
If you can view this page, your web server is correctly installed and accessible
through your firewall.
When the installation is finished, it’s recommended that you run a security
script that comes pre-installed with MySQL. This script will remove some
insecure default settings and lock down access to your database system.
Warning: As of July 2022, an error will occur when you run
the mysql_secure_installation script without some further configuration. The reason is
that this script will attempt to set a password for the installation’s root MySQL account but,
by default on Ubuntu installations, this account is not configured to connect using a
password.
Prior to July 2022, this script would silently fail after attempting to set the root account
password and continue on with the rest of the prompts. However, as of this writing the script
will return the following error after you enter and confirm a password:
Output
... Failed! Error: SET PASSWORD has no significance for user
'root'@'localhost' as the authentication method used doesn't store
authentication data in the MySQL server. Please consider using ALTER USER
instead if you want to change authentication parameters.
New password:
This will lead the script into a recursive loop which you can only get out of by closing your
terminal window.
$ sudo mysql
Then run the following ALTER USER command to change the root user’s authentication
method to one that uses a password. The following example changes the authentication
method to mysql_native_password:
> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password
BY 'password';
> exit
Following that, you can run the mysql_secure_installation script without issue.
$ sudo mysql_secure_installation
This will ask if you want to configure the VALIDATE PASSWORD PLUGIN.
Note: Enabling this feature is something of a judgment call. If enabled, passwords which
don’t match the specified criteria will be rejected by MySQL with an error. It is safe to leave
validation disabled, but you should always use strong, unique passwords for database
credentials.
Regardless of whether you chose to set up the VALIDATE PASSWORD PLUGIN, your
server will next ask you to select and confirm a password for the
MySQL root user. This is not to be confused with the system root.
The database root user is an administrative user with full privileges over the
database system. Even though the default authentication method for the
MySQL root user doesn’t involve using a password, even when one is set,
you should define a strong password here as an additional safety measure.
If you enabled password validation, you’ll be shown the password strength for
the root password you just entered and your server will ask if you want to
continue with that password. If you are happy with your current password,
enter Y for “yes” at the prompt:
Estimated strength of the password: 100
Do you wish to continue with the password provided?(Press y|Y for Yes, any
other key for No) : y
For the rest of the questions, press Y and hit the ENTER key at each prompt.
This will remove some anonymous users and the test database, disable
remote root logins, and load these new rules so that MySQL immediately
respects the changes you have made.
When you’re finished, test whether you’re able to log in to the MySQL console
by typing:
$ sudo mysql
Type 'help;' or '\h' for help. Type '\c' to clear the current input
statement.
mysql>
> exit
Notice that you didn’t need to provide a password to connect as the root user,
even though you have defined one when running
the mysql_secure_installation script. That is because the default
authentication method for the administrative MySQL user
is unix_socket instead of password. Even though this might seem like a security
concern, it makes the database server more secure because the only users
allowed to log in as the root MySQL user are the system users with sudo
privileges connecting from the console or through an application running with
the same privileges. In practical terms, that means you won’t be able to use
the administrative database root user to connect from your PHP application.
Setting a password for the root MySQL account works as a safeguard, in
case the default authentication method is changed
from unix_socket to password.
For increased security, it’s best to have dedicated user accounts with less
expansive privileges set up for every database, especially if you plan on
having multiple databases hosted on your server.
Note: There are some older versions of PHP that doesn’t
support caching_sha2_password, the default authentication method for MySQL 8. For that
reason, when creating database users for PHP applications on MySQL 8, you may need to
configure your application to use the mysql_native_password plug-in instead. This tutorial
will demonstrate how to do that in Step 6.
Your MySQL server is now installed and secured. Next, you’ll install PHP, the
final component in the LAMP stack.
$ php -v
Output
PHP 8.1.2 (cli) (built: Mar 4 2022 18:13:46) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.2, Copyright (c) Zend Technologies
with Zend OPcache v8.1.2, Copyright (c), by Zend Technologies
At this point, your LAMP stack is fully operational, but before testing your
setup with a PHP script, it’s best to set up a proper Apache Virtual Host to
hold your website’s files and folders.
This will create a new blank file. Add in the following bare-bones configuration
with your own domain name:
/etc/apache2/sites-available/your_domain.conf
<VirtualHost *:80>
ServerName your_domain
ServerAlias www.your_domain
ServerAdmin webmaster@localhost
DocumentRoot /var/www/your_domain
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Save and close the file when you’re done. If you’re using nano, do that by
pressing CTRL+X, then Y and ENTER.
With this VirtualHost configuration, we’re telling Apache to
serve your_domain using /var/www/your_domain as the web root directory. If
you’d like to test Apache without a domain name, you can remove or
comment out the options ServerName and ServerAlias by adding a pound sign
(#) the beginning of each option’s lines.
Now, use a2ensite to enable the new virtual host:
To make sure your configuration file doesn’t contain syntax errors, run the
following command:
Your new website is now active, but the web root /var/www/your_domain is still
empty. Create an index.html file in that location to test that the virtual host
works as expected:
$ nano /var/www/your_domain/index.html
Save and close the file, then go to your browser and access your server’s
domain name or IP address:
http://server_domain_or_IP
Your web page should reflect the contents in the file you just edited:
You can leave this file in place as a temporary landing page for your
application until you set up an index.php file to replace it. Once you do that,
remember to remove or rename the index.html file from your document root,
as it would take precedence over an index.php file by default.
After saving and closing the file, you’ll need to reload Apache so the changes
take effect:
In the next step, we’ll create a PHP script to test that PHP is correctly installed
and configured on your server.
Create a new file named info.php inside your custom web root folder:
$ nano /var/www/your_domain/info.php
This will open a blank file. Add the following text, which is valid PHP code,
inside the file:
/var/www/your_domain/info.php
<?php
phpinfo();
To test this script, go to your web browser and access your server’s domain
name or IP address, followed by the script name, which in this case
is info.php:
http://server_domain_or_IP/info.php
Here is an example of the default PHP web page:
This page provides information about your server from the perspective of
PHP. It is useful for debugging and to ensure that your settings are being
applied correctly.
If you see this page in your browser, then your PHP installation is working as
expected.
After checking the relevant information about your PHP server through that
page, it’s best to remove the file you created as it contains sensitive
information about your PHP environment and your Ubuntu server. Use rm to
do so:
$ sudo rm /var/www/your_domain/info.php
You can always recreate this page if you need to access the information again
later.
$ sudo mysql
To create a new database, run the following command from your MySQL
console:
Now create a new user and grant them full privileges on the custom database
you’ve just created.
> exit
Test if the new user has the proper permissions by logging in to the MySQL
console again, this time using the custom user credentials:
$ mysql -u example_user -p
Notice the -p flag in this command, which will prompt you for the password
used when creating the example_user user. After logging in to the MySQL
console, confirm that you have access to the example_database database:
Output
+--------------------+
| Database |
+--------------------+
| example_database |
| information_schema |
+--------------------+
2 rows in set (0.000 sec)
Next, create a test table named todo_list. From the MySQL console, run the
following statement:
> CREATE TABLE example_database.todo_list (
item_id INT AUTO_INCREMENT,
content VARCHAR(255),
PRIMARY KEY(item_id)
);
Insert a few rows of content in the test table. Repeat the next command a few
times, using different values, to populate your test table:
To confirm that the data was successfully saved to your table, run:
Output
+---------+--------------------------+
| item_id | content |
+---------+--------------------------+
| 1 | My first important item |
| 2 | My second important item |
| 3 | My third important item |
| 4 | and this one more thing |
+---------+--------------------------+
4 rows in set (0.000 sec)
After confirming that you have valid data in your test table, exit the MySQL
console:
> exit
Now you can create the PHP script that will connect to MySQL and query for
your content. Create a new PHP file in your custom web root directory using
your preferred editor:
$ nano /var/www/your_domain/todo_list.php
The following PHP script connects to the MySQL database and queries for the
content of the todo_list table, exhibiting the results in a list. If there’s a
problem with the database connection, it will throw an exception.
Add this content into your todo_list.php script, remembering to replace
the example_user and password with your own:
/var/www/your_domain/todo_list.php
<?php
$user = "example_user";
$password = "password";
$database = "example_database";
$table = "todo_list";
try {
$db = new PDO("mysql:host=localhost;dbname=$database", $user,
$password);
echo "<h2>TODO</h2><ol>";
foreach($db->query("SELECT content FROM $table") as $row) {
echo "<li>" . $row['content'] . "</li>";
}
echo "</ol>";
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
Save and close the file when you’re done editing.
You can now access this page in your web browser by visiting the domain
name or public IP address configured for your website, followed
by /todo_list.php:
http://your_domain_or_IP/todo_list.php
This web page should reveal the content you’ve inserted in your test table to
your visitor:
That means your PHP environment is ready to connect and interact with your
MySQL server.
Conclusion
In this guide, you’ve built a flexible foundation for serving PHP websites and
applications to your visitors, using Apache as a web server and MySQL as a
database system.
As an immediate next step, you should ensure that connections to your web
server are secured, by serving them via HTTPS. In order to accomplish that,
you can use Let’s Encrypt to secure your site with a free TLS/SSL certificate.