Introduction:
A “LAMP” stack is a collection of open-source software that is put together on a server to allow it
to run dynamic websites and web applications.This word is an acronym for the Linux operating
system, which is used in conjunction with the Apache webserver. The site’s data is housed in a
MariaDB database, while PHP handles dynamic content.
Although MySQL is commonly used as the database management system in this software
stack, certain Linux editions, including Debian, employ MariaDB as a drop-in alternative for
MySQL.We’ll set up a LAMP stack on a Debian 10 server, with MariaDB as the database
management system, in this tutorial.
Prerequisites:
You’ll need a Debian 10 server with a non-root sudo-enabled user account and a simple firewall
to finish this guide. This can be set up following our Debian 10 initial server setup tutorial.
Step 1 — Installing Apache and Updating the Firewall
You’ll need a Debian 10 server with a non-root sudo-enabled user account and a simple firewall
to finish this guide. This can be set up following our Debian 10 initial server setup tutorial.
APT, Debian’s package management, can be used to install Apache:
# sudo apt update # sudo apt install apache2
These activities are performed with root privileges because this is a Sudo command. To validate
your intentions, it will ask for your usual user’s password.
After you’ve supplied your password, apt will tell you which packages it intends to install and
how much additional disc space it’ll require. To continue, press Y and then ENTER, and the
installation will begin.
Next, verify that your firewall accepts HTTP and HTTPS traffic, assuming you followed the initial
server setup steps by installing and enabling the UFW firewall.
When you install UFW on Debian 10, it comes with app profiles that you may use to customize
your firewall settings. Run the following command to see the full list of application profiles:
# sudo ufw app list
Web servers utilize the WWW profiles to manage their ports:
Available applications:
. . .
WWW
WWW Cache
WWW Full
WWW Secure
. . .
When you look at the WWW Full profile, you’ll notice that it allows traffic on ports 80 and 443:
# sudo ufw app info "WWW Full"
Profile: WWW Full
Title: Web Server (HTTP,HTTPS)
Description: Web Server (HTTP,HTTPS)
Ports:
80,443/tcp
For this profile, allow incoming HTTP and HTTPS traffic:
# sudo ufw allow in "WWW Full"
By visiting your server’s public IP address in your web browser and verifying that everything
happened as intended, you can run a spot check straight away to ensure that everything went
as expected:
http://your_server_ip
The default Debian 10 Apache web page will appear, which is provided for information and
testing purposes. This is what it should look like:
If this page appears, your web server is now properly configured and accessible through your
firewall.
There are several techniques to determine your server’s public IP address if you don’t know it.
This is usually the IP that you use to connect to your server using SSH.
You may do this from the command line in a few different ways. To begin, type the following into
the iproute2 tools to obtain your IP address:
# ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'
You’ll get two or three lines back as a result of this. Although they are all valid addresses, your
computer may only be able to use one of them, so try them all.
Another option is to use the curl program to contact an external party and ask them to tell you
how they see your server. This is done by inquiring about your IP address with a certain server:
# sudo apt install curl # curl http://icanhazip.com
To access the default Apache page, type your IP address into your web browser’s address bar,
regardless of how you got it.
Step 2 — Installing MariaDB
After you’ve set up a web server, you’ll need to set up a database system so that you can store
and manage data for your website.
In Debian 10, the default-MySQL-server replaced the meta-package MySQL-server, which was
previously used to install the MySQL server. This meta-package refers to MariaDB, a community
clone of Oracle’s original MySQL server that is currently the default MySQL-compatible
database server in Debian-based package manager repositories.
However, instead of utilizing the meta-package, you should install MariaDB using the program’s
actual package, MariaDB-server, for longer-term compatibility.
Run the following command to install this software:
# sudo apt install mariadb-server
It’s advised that you run a security script that comes pre-installed with MariaDB after the
installation is complete. This script will lock down access to your database system by removing
some insecure default settings. To begin the interactive script, type:
# sudo mysql_secure_installation
This script will guide you through a series of prompts that will allow you to make changes to your
MariaDB configuration. You’ll be prompted to enter the current database root password at the
first prompt. This is not to be confused with the root of the operating system. The database root
user is a database administrator who has full control over the database system. This password
will be blank because you just installed MariaDB and haven’t made any configuration changes
yet, so simply press ENTER at the prompt.
The following question asks if you want to create a database root password. You don’t need to
configure this currently because MariaDB utilizes a special authentication technique for the root
user that is often safer than using a password. Press ENTER after typing N.
You can now accept the defaults for all further questions by pressing Y and then ENTER. This
will delete anonymous users and the test database, disable remote root login, and load these
new rules, ensuring that MariaDB recognizes your changes right away. When you’re ready, go to
the MariaDB console and type:
# sudo mariadb
The use of sudo when performing this command infers that this will connect to the MariaDB
server as the administrator database user root. This is what you should get as a result:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 74
Server version: 10.3.15-MariaDB-1 Debian 10
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>
To connect as the root user, you didn’t need to give a password. This works because the
administrator MariaDB user’s default authentication method is Unix socket rather than a
password. Although this may appear to be a security risk at first glance, it strengthens the
database server’s security by allowing only system users with sudo access to login through the
console or through an application running with the same privileges to log in as the root MariaDB
user. In practice, this means you won’t be able to connect from your PHP application using the
administrative database root user.
It’s recommended to set up dedicated user accounts with fewer privileges for each database,
especially if you plan on hosting numerous databases on your server, for added protection. We’ll
establish a database called example database and a user called example user to show how this
works, but you can use whatever name you like. Run the following command from your MariaDB
console to create a new database:
CREATE DATABASE example_database;
You may now create a new user and give them full access to the custom database you just
made. The following command sets the password for this user to password, but you should
replace it with a secure password of your choice.
GRANT ALL ON example_database.* TO ‘example_user’@’localhost’ IDENTIFIED BY
‘password’ WITH GRANT OPTION;
This will grant the example user complete access to the example database, but it will restrict the
user from creating or changing any other databases on your server.
To guarantee that privileges are saved and available in the current session, flush them:
MariaDB\s[(none)]> FLUSH PRIVILEGES;
Exit the MariaDB shell after that:
MariaDB\s[(none)]> exit;
By connecting into the MariaDB console again, this time using the custom user credentials, you
can see if the new user has the correct permissions:
# mariadb -u example_user -p
This command includes the -p flag, which prompts you for the password you used to create the
example user user. Verify that you have access to the example database db after logging into
the MariaDB console:
MariaDB\s[(none)]> SHOW DATABASES;
You’ll get the following output as a result of this
+--------------------+
| Database |
+--------------------+
| example_database |
| information_schema |
+--------------------+
2 rows in set (0.000 sec)
Type: to quit the MariaDB shell.
MariaDB\s[(none)]> exit;
Your database system is now up and running, and you can proceed to installing PHP, the final
component of the LAMP stack.
Step 3 — Installing PHP
PHP is the part of your system that processes code in order to show dynamic content. It can
execute scripts, connect to MariaDB databases to retrieve data, and then provide the processed
content to your web server for display.
Use the apt system to install PHP once more. Include the following assistance packages to
ensure that PHP code may execute on the Apache server and communicate with your MariaDB
database:
# sudo apt install php libapache2-mod-php php-mysql
This should complete the installation of PHP without any issues. In a moment, we’ll put this to
the test.
Most of the time, you’ll want to change the way Apache serves files. When a user requests a
directory from the server, Apache looks for a file called index.html first. Make Apache seek for
an index.php file first to signal the web server that PHP files are preferred over others.
To do so, open the dir. conf file in a text editor with root privileges with the following command:
# sudo nano /etc/apache2/mods-enabled/dir.conf
It will look like this:
<IfModule mod_dir.c>
DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm
</IfModule>
After the DirectoryIndex specification, move the PHP index file (highlighted above) to the first
location, as follows:
<IfModule mod_dir.c>
DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>
Save and close the file when you’re finished. If you’re using nano, you can confirm by pressing
CTRL+X, then Y, then ENTER.
Reload Apache’s configuration now by typing:
# sudo systemctl reload apache2
systemctl status can be used to verify the status of the apache2 service:
# sudo systemctl status apache2
● apache2.service - The Apache HTTP Server
Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2019-07-08 12:58:31 UTC; 8s ago
Docs: https://httpd.apache.org/docs/2.4/
Process: 11948 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS)
Main PID: 11954 (apache2)
Tasks: 6 (limit: 4719)
Memory: 11.5M
CGroup: /system.slice/apache2.service
├─11954 /usr/sbin/apache2 -k start
├─11955 /usr/sbin/apache2 -k start
├─11956 /usr/sbin/apache2 -k start
├─11957 /usr/sbin/apache2 -k start
├─11958 /usr/sbin/apache2 -k start
└─11959 /usr/sbin/apache2 -k start
Your LAMP stack is now completely functional, but before you can test it with a PHP script, you
should create an Apache Virtual Host to house your website’s files and folders. That will be
done in the next stage.
Step 4 — Creating a Virtual Host for your Website
Apache serves its content by default from the /var/www/HTML directory, using the settings in
/etc/apache2/sites-available/000-default.conf. We’ll construct a new virtual host for testing your
PHP environment rather than altering the default website configuration file. We can use virtual
hosts to host numerous websites on a single Apache server.
After that, you’ll establish a directory structure for an example website called your domain in
/var/www.
Make the following changes to your domain’s root web directory:
# sudo mkdir /var/www/your_domain
Next, use the $USER environment variable to assign ownership to the directory, which should
refer to your current system user:
# sudo chown -R $USER:$USER /var/www/your_domain
Then, using your command-line editor, create a new configuration file in Apache’s
sites-available directory. We’ll use nano in this case:
# sudo nano /etc/apache2/sites-available/your_domain.conf
This will start a fresh blank document. Paste in the bare-bones setup below:
<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>
We’re telling Apache to serve your domain from /var/www/your domain as the webroot directory
with this VirtualHost configuration. Remove or comment out the parameters ServerName and
ServerAlias by adding a # character to the beginning of each option’s line if you want to test
Apache without a domain name.
You may now enable this virtual host using a2ensite:
# sudo a2ensite your_domain
It’s possible that you’ll wish to turn off Apache’s default webpage. If you’re not using a custom
domain name, this is needed because Apache’s default configuration will otherwise replace your
Virtual Host. Type: to turn off Apache’s default website:
# sudo a2dissite 000-default
You can use the following command to ensure your configuration file is free of syntax errors:
# sudo apache2ctl configtest
Finally, reload Apache so these changes take effect:
# sudo systemctl reload apache2
Your new website is up and running, but the web root /var/www/your_domain is still empty. We’ll
develop a PHP script to test the new setup and ensure that PHP is installed and configured
appropriately on your server in the next step.
Step 5 — Testing PHP Processing on your Web Server
We’ll construct a basic PHP test script to confirm that Apache can handle and process requests
for PHP files now that you have a custom location to host your website’s files and folders.
Inside your custom web root folder, create a new file called info.php:
# nano /var/www/your_domain/info.php
This will create a new file with no content. Inside the file, add the following text, which is
legitimate PHP code:
<?php
phpinfo();
Save and close the file when you’re finished.
Now you can see if your web server can display the content generated by this PHP script
successfully. To give it a shot, go to this page in your browser. You’ll need the public IP address
of your server once more.
You should go to the following address:
http://your_domain/info.php
From the standpoint of PHP, this page gives some basic information about your server. It’s
helpful for troubleshooting and ensuring that your settings are implemented correctly.
f this page appears in your browser, your PHP installation is running properly.
It’s advisable to delete the file you created after checking the pertinent information about your
PHP server on that page, as it contains critical information about your PHP environment and
your Debian server. You can accomplish this with the command rm:
# sudo rm /var/www/your_domain/info.php
Step 6 — Testing Database Connection from PHP (Optional)
You can create a test table with dummy data and query its contents from a PHP script to see if
PHP is able to connect to MariaDB and execute database queries.
To begin, log in to the MariaDB console using the database user you created in Step 2:
# mariadb -u example_user -p
Create a table named todo_list. From the MariaDB console, run the following statement:
MariaDB\s[(none)]> CREATE TABLE example_database.todo_list ( MariaDB\s[(none)]> item_id INT AUTO_INCREMENT, MariaDB\s[(none)]> content VARCHAR(255), MariaDB\s[(none)]> PRIMARY KEY(item_id) MariaDB\s[(none)]> );
Add a few rows of material to the test table now. You might wish to run the following command a
few times with different values each time:
Run the following command to see if the data was properly saved to your table
MariaDB\s[(none)]> INSERT INTO example_database.todo_list (content) VALUES ("My first important item");
To confirm that the data was successfully saved to your table, run:
MariaDB\s[(none)]> SELECT * FROM example_database.todo_list;
The following output will appear:
+---------+--------------------------+
| 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)
You can exit the MariaDB console after ensuring that your test table has valid data:
MariaDB\s[(none)]> exit
You may now write the PHP script that connects to MariaDB and searches for your data. Using
your favourite editor, create a new PHP file in your custom site root directory. We’ll use nano for
that:
nano /var/www/your_domain/todo_list.php
The following PHP script connects to the MariaDB database and searches the todo list table for
content, returning a list of results. It will throw an exception if there is an issue with the database
connection. Copy and paste the following into your todo list.php script:
<?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();
}
ou may now reach this page in your web browser by going to your website’s domain name or
public IP address and then typing by /todo_list.php:
http://your_domain/todo_list.php
You should see something similar to this page, which shows the content you’ve added to your
test table:
That indicates your PHP environment is ready to connect to your MariaDB server and
communicate with it.
Conclusion
Using Apache as the web server and MariaDB as the database system, we’ve established a
flexible basis for serving PHP websites and apps to your users in this article.
You can improve your present setup by installing Composer for dependency and package
management in PHP, as well as a Let’s Encrypt OpenSSL certificate for your website.
Thank you it helped me a lot !