Ubuntu how to install lamp ubuntu
Ubuntu how to install lamp ubuntu
LAMP Applications
Overview
LAMP installations (Linux + Apache + MySQL + PHP/Perl/Python) are a popular setup for Ubuntu servers. There is a plethora of Open Source applications written using the LAMP application stack. Some popular LAMP applications are Wiki’s, Content Management Systems, and Management Software such as phpMyAdmin.
One advantage of LAMP is the substantial flexibility for different database, web server, and scripting languages. Popular substitutes for MySQL include PostgreSQL and SQLite. Python, Perl, and Ruby are also frequently used instead of PHP. While Nginx, Cherokee and Lighttpd can replace Apache.
The fastest way to get started is to install LAMP using tasksel. Tasksel is a Debian/Ubuntu tool that installs multiple related packages as a co-ordinated “task” onto your system. To install a LAMP server:
At a terminal prompt enter the following command:
After installing it you’ll be able to install most LAMP applications in this way:
Download an archive containing the application source files.
Unpack the archive, usually in a directory accessible to a web server.
Depending on where the source was extracted, configure a web server to serve the files.
Configure the application to connect to the database.
Run a script, or browse to a page of the application, to install the database needed by the application.
Once the steps above, or similar steps, are completed you are ready to begin using the application.
A disadvantage of using this approach is that the application files are not placed in the file system in a standard way, which can cause confusion as to where the application is installed. Another larger disadvantage is updating the application. When a new version is released, the same process used to install the application is needed to apply updates.
Fortunately, a number of LAMP applications are already packaged for Ubuntu, and are available for installation in the same way as non-LAMP applications. Depending on the application some extra configuration and setup steps may be needed, however.
This section covers how to install some LAMP applications.
phpMyAdmin
phpMyAdmin is a LAMP application specifically written for administering MySQL servers. Written in PHP, and accessed through a web browser, phpMyAdmin provides a graphical interface for database administration tasks.
Installation
Before installing phpMyAdmin you will need access to a MySQL database either on the same host as that phpMyAdmin is installed on, or on a host accessible over the network. For more information see MySQL documentation. From a terminal prompt enter:
At the prompt choose which web server to be configured for phpMyAdmin. The rest of this section will use Apache2 for the web server.
Once logged in you can reset the root password if needed, create users, create/destroy databases and tables, etc.
Configuration
To use phpMyAdmin to administer a MySQL database hosted on another server, adjust the following in /etc/phpmyadmin/config.inc.php :
Replace db_server with the actual remote database server name or IP address. Also, be sure that the phpMyAdmin host has permissions to access the remote database.
Once configured, log out of phpMyAdmin and back in, and you should be accessing the new server.
The config.header.inc.php and config.footer.inc.php files in /etc/phpmyadmin directory are used to add a HTML header and footer to phpMyAdmin.
For more information on configuring Apache2 see this documentation.
References
The phpMyAdmin documentation comes installed with the package and can be accessed from the phpMyAdmin Documentation link (a question mark with a box around it) under the phpMyAdmin logo. The official docs can also be access on the phpMyAdmin site.
Another resource is the phpMyAdmin Ubuntu Wiki page.
WordPress
WordPress is a blog tool, publishing platform and CMS implemented in PHP and licensed under the GNU GPLv2.
Installation
To install WordPress, run the following comand in the command prompt:
You should also install apache2 web server and mysql server. For installing apache2 web server, please refer to Apache2 documentation. For installing mysql server, please refer to MySQL documentation.
Configuration
For configuring your first WordPress application, configure an apache site. Open /etc/apache2/sites-available/wordpress.conf and write the following lines:
Enable this new WordPress site
Once you configure the apache2 web server and make it ready for your WordPress application, you should restart it. You can run the following command to restart the apache2 web server:
To facilitate multiple WordPress installations, the name of this configuration file is based on the Host header of the HTTP request. This means that you can have a configuration per VirtualHost by simply matching the hostname portion of this configuration with your Apache Virtual Host. e.g. /etc/wordpress/config-10.211.55.50.php, /etc/wordpress/config-hostalias1.php, etc. These instructions assume you can access Apache via the localhost hostname (perhaps by using an ssh tunnel) if not, replace /etc/wordpress/config-localhost.php with /etc/wordpress/config-NAME_OF_YOUR_VIRTUAL_HOST.php.
Once the configuration file is written, it is up to you to choose a convention for username and password to mysql for each WordPress database instance. This documentation shows only one, localhost, example.
Now configure WordPress to use a mysql database. Open /etc/wordpress/config-localhost.php file and write the following lines:
Now create this mysql database. Open a temporary file with mysql commands wordpress.sql and write the following lines:
Execute these commands.
Note the generated password (if applicable) and click the login password. Your WordPress is now ready for use.
How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu 18.04
Introduction
A “LAMP” stack is a group of open-source software that is typically installed together to enable a server to host dynamic websites and web apps. This term is actually 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.
In this guide, we’ll install a LAMP stack on an Ubuntu 18.04 server.
Prerequisites
Step 1 — Installing Apache and Updating the Firewall
The Apache web server is a popular open source web server that can be used along with PHP to host dynamic websites. It’s well-documented and has been in wide use for much of the history of the web.
First, make sure your apt cache is updated with:
If this is your first time using sudo in this session, you’ll be prompted to provide your regular user’s password to validate your permissions.
Once the cache has been updated, you can install Apache with:
After entering this command, apt will tell you which packages it plans to install and how much extra disk space they’ll take up. Press Y and hit ENTER to confirm, and the installation will proceed.
Adjust the Firewall to Allow Web Traffic
Next, assuming that you have followed the initial server setup instructions and enabled the UFW firewall, make sure that your firewall allows HTTP and HTTPS traffic. You can check that UFW has an application profile for Apache like so:
If you look at the Apache Full profile details, you’ll see that it enables traffic to ports 80 and 443 :
To allow incoming HTTP and HTTPS traffic for this server, run:
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 (see the note under the next heading to find out what your public IP address is if you do not have this information already):
You will see the default Ubuntu 18.04 Apache web page, which is there for informational and testing purposes. It should look something like this:
If you see this page, then your web server is now correctly installed and accessible through your firewall.
How To Find your Server’s Public IP Address
If you do not know what your server’s public IP address is, there are a number of ways you can find it. Usually, this is the address you use to connect to your server through SSH.
There are a few different ways to do this from the command line. First, you could use the iproute2 tools to get your IP address by typing this:
This will give you two or three lines back. They are all correct addresses, but your computer may only be able to use one of them, so feel free to try each one.
An alternative method is to use the curl utility to contact an outside party to tell you how it sees your server. This is done by asking a specific server what your IP address is:
Regardless of the method you use to get your IP address, type it into your web browser’s address bar to view the default Apache page.
Step 2 — Installing MySQL
Now that you have your web server up and running, it is time to install MySQL. MySQL is a database management system. Basically, it will organize and provide access to databases where your site can store information.
Again, use apt to acquire and install this software:
Note: In this case, you do not have to run sudo apt update prior to the command. This is because you recently ran it in the commands above to install Apache. The package index on your computer should already be up-to-date.
This command, too, will show you a list of the packages that will be installed, along with the amount of disk space they’ll take up. Enter Y to continue.
When the installation is complete, run a simple security script that comes pre-installed with MySQL which will remove some dangerous defaults and lock down access to your database system. Start the interactive script by running:
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. This will cause issues if you use a weak password in conjunction with software which automatically configures MySQL user credentials, such as the Ubuntu packages for phpMyAdmin. It is safe to leave validation disabled, but you should always use strong, unique passwords for database credentials.
Answer Y for yes, or anything else to continue without enabling.
If you answer “yes”, you’ll be asked to select a level of password validation. Keep in mind that if you enter 2 for the strongest level, you will receive errors when attempting to set any password which does not contain numbers, upper and lowercase letters, and special characters, or which is based on common dictionary words.
If you’ve 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 change that password. If you are happy with your current password, enter N for “no” at the prompt:
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 if you’re able to log in to the MySQL console by typing:
This will connect to the MySQL server as the administrative database user root, which is inferred by the use of sudo when running this command. You should see output like this:
To exit the MySQL console, type:
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. Please refer to our guide on How To Create a New User and Grant Permissions on MySQL for detailed instructions on how to create MySQL users and configure database access rights.
Your MySQL server is now installed and secured. Next, we’ll install PHP, the final component in the LAMP stack.
Step 3 — Installing PHP
PHP is the component of your setup that will process code to display dynamic content. It can run scripts, connect to your MySQL databases to get information, and hand the processed content over to your web server so that it can display the results to your visitors.
Once again, leverage the apt system to install PHP. In addition to the php package, you’ll also need libapache2-mod-php to integrate PHP into Apache, and the php-mysql package to allow PHP to connect to MySQL databases. Run the following command to install all three packages and their dependencies:
This should install PHP without any problems. We’ll test this in a moment.
Changing Apache’s Directory Index (Optional)
To make this change, open the dir.conf configuration file in a text editor of your choice. Here, we’ll use nano :
It will look like this:
Move the PHP index file (highlighted above) to the first position after the DirectoryIndex specification, like this:
After this, restart the Apache web server in order for your changes to be recognized. You can do that with the following command:
You can also check on the status of the apache2 service using systemctl :
Press Q to exit this status output.
Installing PHP Extensions (Optional)
Use the arrow keys to scroll up and down, and press Q to quit.
The results are all optional components that you can install. It will give you a short description for each:
To learn more about what each module does, you could search the internet for more information about them. Alternatively, look at the long description of the package by typing:
There will be a lot of output, with one field called Description which will have a longer explanation of the functionality that the module provides.
For example, to find out what the php-cli module does, you could type this:
Along with a large amount of other information, you’ll find something that looks like this:
If, after researching, you decide you would like to install a package, you can do so by using the apt install command like you have been doing for the other software.
If you decided that php-cli is something that you need, you could type:
If you want to install more than one module, you can do that by listing each one, separated by a space, following the apt install command, like this:
At this point, your LAMP stack is installed and configured. Before you do anything else, we recommend that you set up an Apache virtual host where you can store your server’s configuration details.
Step 4 — Setting Up a Virtual Host (Recommended)
When using the Apache web server, you can use virtual hosts (similar to server blocks in Nginx) to encapsulate configuration details and host more than one domain from a single server. We will set up a domain called your_domain, but you should replace this with your own domain name. To learn more about setting up a domain name with DigitalOcean, see our Introduction to DigitalOcean DNS.
Create the directory for your_domain as follows:
The permissions of your web root directory should be correct if you haven’t modified its umask value, but you can make sure by typing:
Next, create a sample index.html page using nano or your favorite editor:
Inside, add the following sample HTML:
Save and close the file when you are finished.
Paste in the following configuration block, which is similar to the default, but updated for our new directory and domain name:
Save and close the file when you are finished.
Let’s enable the file with the a2ensite tool:
Disable the default site defined in 000-default.conf :
Next, let’s test for configuration errors:
You should see the following output:
Restart Apache to implement your changes:
With that, your virtual host is fully set up. Before making any more changes or deploying an application, though, it would be helpful to proactively test out your PHP configuration in case there are any issues that should be addressed.
Step 5 — Testing PHP Processing on your Web Server
Create the file at the web root you created in the previous step by running:
This will open a blank file. Add the following text, which is valid PHP code, inside the file:
When you are finished, save and close the file.
Now you can test whether your web server is able to correctly display content generated by this PHP script. To try this out, visit this page in your web browser. You’ll need your server’s public IP address or domain name again.
The address you will want to visit is:
The page that you come to should look something like this:
This page provides some basic 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 can see this page in your browser, then your PHP is working as expected.
You probably want to remove this file after this test because it could actually give information about your server to unauthorized users. To do this, run the following command:
You can always recreate this page if you need to access the information again later.
Conclusion
Now that you have a LAMP stack installed, you have many choices for what to do next. You’ve installed a platform that will allow you to install most kinds of websites and web software on your server.
As an immediate next step, you should ensure that connections to your web server are secured, by serving them via HTTPS. Follow our guide on how to secure Apache with Let’s Encrypt to secure your site with a free TLS/SSL certificate.
Some other popular options are:
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
Установка LAMP Ubuntu 18.04
В этой статье мы рассмотрим, как выполняется Установка LAMP Ubuntu 18.04 несколькими способами: с помощью утилиты tasksel или вручную с помощью установщика программ.
Установка LAMP в Ubuntu
1. Установка пакетов с помощью tasksel
sudo apt install tasksel
Затем, чтобы установить Lamp на Ubuntu, достаточно выполнить такую команду:
sudo tasksel install lamp-server
Установка займёт кое-какое время, потому что утилите придётся скачать и настроить все пакеты, но потом вы получите полностью работающий стек LAMP.
2. Как установить Lamp в Ubuntu вручную
Если вы не хотите использовать tasksel, вы можете установить все пакеты по отдельности и настроить их для совместной работы. Сначала установим все необходимые пакеты. Установка последней версии Apache2 из репозиториев:
sudo apt install apache2
Установка базы данных MariaDB из репозиториев:
sudo apt install mariadb-server
Или вы можете установить MySQL:
sudo apt install mysql-server
Установка интерпретатора языка программирования PHP 7.2 и расширений, необходимых для его работы с Apache и MySQL:
sudo apt install php7.2 libapache2-mod-php7.2 php-mysql
Установка дополнительных расширений для PHP, которые вам понадобятся в будущем для хостинга большинства популярных проектов:
sudo apt install php-curl php-json php-cgi php-gd php-zip php-mbstring php-xml php-xmlrpc
3. Настройка брандмауэра
По умолчанию брандмауэр закрывает все неразрешённые входящие подключения. Поэтому, чтобы к вашему веб-серверу можно было получить доступ извне, необходимо добавить его порт в исключения:
sudo ufw allow in 80/tcp
4. Проверка работы LAMP
Для проверки наберите в адресной строке браузера IP-адрес сервера, куда вы устанавливали LAMP, у меня это localhost:
Работает, теперь давайте проверим, правильно ли работает PHP. Создайте файл в директории /var/www/html со следующим содержимым:
sudo vi /var/www/html/phpinfo.php
Затем откройте адрес localhost/phpinfo.php. Если всё работает, вы должны увидеть такую страничку:
Также можно проверить, работает ли MySQL: если расширение PHP для MySQL загрузилось, то на странице phpinfo будет размещена такая информация:
Готово, дальше идёт в основном настройка LAMP в Ubuntu 18.04.
5. Настройка Apache
Для обработки запросов будет использоваться модуль mpm_prefork, так как он совместим с большинством систем. Поэтому его нужно активировать, а mpm_event и mpm_worker отключить:
sudo a2dismod mpm_event
sudo a2dismod mpm_worker
sudo a2enmod mpm_prefork
Включаем mod_rewrite, который сейчас используется практически везде:
sudo a2enmod rewrite
Если вы хотите использовать файлы httaccess для настроек, то необходимо в файле /etc/apache2/apache2.conf изменить значение AllowOverride с None на All для нужных местоположений, например, для /var/www:
sudo vi /etc/apache2/apache2.conf
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
Далее необходимо перезапустить Apache:
sudo systemctl restart apache2
Подробнее про настройку веб-сервера читайте в отдельной статье установка и настройка Apache.
6. Настройка PHP
По умолчанию короткие теги, обрамляющие скрипты PHP, отключены. Это может привести к тому, что некоторые скрипты, использующие эти теги, могут не выполнятся. Для включения этой возможности откройте файл:
sudo vi /etc/php/7.2/apache2/php.ini
Найдите short_open_tag = Off и замените на:
Вывод ошибок в PHP по умолчанию тоже отключён. Если вы хотите разрабатывать программы на этом сервере, то вам необходимо включить ошибки, иначе вместо ошибок вы будете видеть пустой экран. Для этого найдите эти строки и приведите их к такому виду:
error_reporting = E_ALL
display_errors = On
Или для записи ошибок в файл вы можете добавить такую строку:
После внесения всех изменений необходимо перезапустить Apache:
sudo systemctl restart apache2
Подробнее про настройку файла php.ini смотрите здесь.
7. Настройка MySQL
По умолчанию MySQL не очень хорошо настроена в плане безопасности. Нам нужно задать пароль суперпользователя и удалить гостевой доступ. Для выполнения всех этих задач запустите в терминале:
На первом этапе утилита попросит вас ввести пароль суперпользователя, так как он ещё не задан, просто нажмите Enter:
Далее введите новый пароль:
Во всех следующих вопросах нужно отвечать утвердительно:
Готово, теперь ваша база данных защищена и готова к работе.
8. Удаление LAMP в Ubuntu
Чтобы полностью удалить LAMP из системы, достаточно удалить все пакеты, которые вы установили ранее:
sudo apt purge apache2 mariadb-server php7.2 libapache2-mod-php7.2 php-mysql php-curl php-json php-cgi php-gd php-zip php-mbstring php-xml php-xmlrpc
Команда purge позволяет удалить не только пакеты, но и их конфигурационные файлы. Если вы хотите оставить конфигурационные файлы, используйте команду remove.
Если установка LAMP на Ubuntu выполнялась с помощью tasksel, то для удаления необходимо выполнить:
sudo tasksel uninstall lamp-server
Выводы
В этой статье мы разобрали, как выполняется установка Apache, PHP, MySQL на Ubuntu 18.04. Как видите, это не очень сложно и с такой задачей может справиться даже новичок, если немного попрактикуется на виртуальной машине. Фактически, уже после шага 3 установка Lamp Ubuntu 18.04 практически завершена, и уже можно работать, а дальше идёт только настройка LAMP. Если у вас остались вопросы, спрашивайте в комментариях!
How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu 20.04
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.
In this guide, you’ll set up a LAMP stack on an Ubuntu 20.04 server.
Prerequisites
Step 1 — Installing Apache and Updating the Firewall
The Apache web server is among the most popular web servers in the world. It’s well documented, has an active community of users, and has been in wide use for much of the history of the web, which makes it a great choice for hosting a website.
Then, install Apache with:
Once the installation is finished, you’ll need to adjust your firewall settings to allow HTTP traffic. UFW has different application profiles that you can leverage for accomplishing that. To list all currently available UFW application profiles, you can run:
You’ll see output like this:
Here’s what each of these profiles mean:
You can verify the change with:
Traffic on port 80 is now allowed through the firewall.
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 (see the note under the next heading to find out what your public IP address is if you do not have this information already):
You’ll see the default Ubuntu 20.04 Apache web page, which is there for informational and testing purposes. It should look something like this:
If you see this page, then your web server is now correctly installed and accessible through your firewall.
How To Find your Server’s Public IP Address
If you do not know what your server’s public IP address is, there are a number of ways you can find it. Usually, this is the address you use to connect to your server through SSH.
There are a few different ways to do this from the command line. First, you could use the iproute2 tools to get your IP address by typing this:
This will give you two or three lines back. They are all correct addresses, but your computer may only be able to use one of them, so feel free to try each one.
An alternative method is to use the curl utility to contact an outside party to tell you how it sees your server. This is done by asking a specific server what your IP address is:
Regardless of the method you use to get your IP address, type it into your web browser’s address bar to view the default Apache page.
Step 2 — Installing MySQL
Now that you have a web server up and running, you need to install the database system to be able to store and manage data for your site. MySQL is a popular database management system used within PHP environments.
Again, use apt to acquire and install this software:
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. Start the interactive script by running:
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.
Answer Y for yes, or anything else to continue without enabling.
If you answer “yes”, you’ll be asked to select a level of password validation. Keep in mind that if you enter 2 for the strongest level, you will receive errors when attempting to set any password which does not contain numbers, upper and lowercase letters, and special characters, or which is based on common dictionary words.
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:
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 if you’re able to log in to the MySQL console by typing:
This will connect to the MySQL server as the administrative database user root, which is inferred by the use of sudo when running this command. You should see output like this:
To exit the MySQL console, type:
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.
Your MySQL server is now installed and secured. Next, we’ll install PHP, the final component in the LAMP stack.
Step 3 — Installing PHP
To install these packages, run:
Once the installation is finished, you can run the following command to confirm your PHP version:
At this point, your LAMP stack is fully operational, but before you can test 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. We’ll do that in the next step.
Step 4 — Creating a Virtual Host for your Website
When using the Apache web server, you can create virtual hosts (similar to server blocks in Nginx) to encapsulate configuration details and host more than one domain from a single server. In this guide, we’ll set up a domain called your_domain, but you should replace this with your own domain name.
Note: In case you are using DigitalOcean as DNS hosting provider, you can check our product docs for detailed instructions on how to set up a new domain name and point it to your server.
Create the directory for your_domain as follows:
Then, open a new configuration file in Apache’s sites-available directory using your preferred command-line editor. Here, we’ll use nano :
This will create a new blank file. Paste in the following bare-bones configuration:
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 # character in the beginning of each option’s lines.
You can now use a2ensite to enable the new virtual host:
You might want to disable the default website that comes installed with Apache. This is required if you’re not using a custom domain name, because in this case Apache’s default configuration would overwrite your virtual host. To disable Apache’s default website, type:
To make sure your configuration file doesn’t contain syntax errors, run:
Finally, reload Apache so these changes take effect:
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 so that we can test that the virtual host works as expected:
Include the following content in this file:
Now go to your browser and access your server’s domain name or IP address once again:
You’ll see a page like this:
If you see this page, it means your Apache virtual host is working as expected.
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.
A Note About DirectoryIndex on Apache
With the default DirectoryIndex settings on Apache, a file named index.html will always take precedence over an index.php file. This is useful for setting up maintenance pages in PHP applications, by creating a temporary index.html file containing an informative message to visitors. Because this page will take precedence over the index.php page, it will then become the landing page for the application. Once maintenance is over, the index.html is renamed or removed from the document root, bringing back the regular application page.
In case you want to change this behavior, you’ll need to edit the /etc/apache2/mods-enabled/dir.conf file and modify the order in which the index.php file is listed within the DirectoryIndex directive:
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.
Step 5 — Testing PHP Processing on your Web Server
Now that you have a custom location to host your website’s files and folders, we’ll create a PHP test script to confirm that Apache is able to handle and process requests for PHP files.
Create a new file named info.php inside your custom web root folder:
This will open a blank file. Add the following text, which is valid PHP code, inside the file:
When you are finished, save and close the file.
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 :
You’ll see a page similar to this:
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 can 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. You can use rm to do so:
You can always recreate this page if you need to access the information again later.
Step 6 — Testing Database Connection from PHP (Optional)
If you want to test whether PHP is able to connect to MySQL and execute database queries, you can create a test table with dummy data and query for its contents from a PHP script. Before we can do that, we need to create a test database and a new MySQL user properly configured to access it.
We’ll create a database named example_database and a user named example_user, but you can replace these names with different values.
First, connect to the MySQL console using the root account:
To create a new database, run the following command from your MySQL console:
Now you can create a new user and grant them full privileges on the custom database you’ve just created.
Now we need to give this user permission over the example_database database:
This will give the example_user user full privileges over the example_database database, while preventing this user from creating or modifying other databases on your server.
Now exit the MySQL shell with:
You can test if the new user has the proper permissions by logging in to the MySQL console again, this time using the custom user credentials:
This will give you the following output:
Next, we’ll create a test table named todo_list. From the MySQL console, run the following statement:
Insert a few rows of content in the test table. You might want to repeat the next command a few times, using different values:
To confirm that the data was successfully saved to your table, run:
You’ll see the following output:
After confirming that you have valid data in your test table, you can exit the MySQL console:
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. We’ll use nano for that:
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. Copy this content into your todo_list.php script:
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 :
You should see a page like this, showing the content you’ve inserted in your test table:
That means your PHP environment is ready to connect and interact with your MySQL server.
Conclusion
In this guide, we’ve built a flexible foundation for serving PHP websites and applications to your visitors, using Apache as web server and MySQL as 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.
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
Search Results
No Results
Filters
How to Install a LAMP Stack on Ubuntu 18.04
What is a LAMP Stack?
A LAMP (Linux, Apache, MySQL, PHP) stack is a common, free, and open-source web stack used for hosting web content in a Linux environment. Many consider it the platform of choice on which to develop and deploy high-performance web apps.
This guide shows how to install and test a LAMP stack on Ubuntu 18.04 (LTS).
All configuration files should be edited with elevated privileges. Remember to include sudo before running your text editor.
Replace each instance of example.com in this guide with your site’s domain name or IP.
Before You Begin
If you have not already done so, create a Linode account and Compute Instance. See our Getting Started with Linode and Creating a Compute Instance guides.
Follow our Setting Up and Securing a Compute Instance guide to update your system and configure your hostname. You may also wish to set the timezone, create a limited user account, and harden SSH access.
Installation
Install Using Tasksel
Instead of installing Apache, MySQL, and PHP separately, Tasksel offers a convenient way to get a LAMP stack running quickly.
Install Tasksel if not already installed by default:
Use Tasksel to install the LAMP stack:
Install Packages Separately
If you prefer not to install the bundled packages via Tasksel, you can instead install them separately:
Install Apache 2.4 from the Ubuntu repository:
Install the mysql-server package:
Install PHP, the PHP Extension and Application Repository, Apache support, and MySQL support:
Optionally, install additional cURL, JSON, and CGI support:
Configuration
Apache
The KeepAlive setting allows Apache to better utilize server-side memory, reducing latency for users on the hosted site. KeepAlive makes a website faster if the host has enough memory to support it. This is done by allowing Apache to reuse connections, instead of opening a new connection for every request.
Open the apache2.conf Apache config file and adjust the KeepAlive setting:
The default multi-processing module (MPM) is the prefork module. mpm_prefork is the module that is compatible with most systems. Open the mpm_prefork.conf file located in /etc/apache2/mods-available and edit the configuration. Below are the suggested values for a 2GB Linode:
Enable the firewall to allow web traffic. This guide lists the commands to enable web traffic if you configured UFW on your server.
a. Check the ports that are enabled for Apache Full Profile:
Ports 80 and 443 should be listed as enabled for Apache Full profile.
b. To allow incoming HTTP and HTTPS traffic for Apache Full profile:
Disable the event module and enable prefork:
Virtual Hosts
You can set up virtual hosts several ways, and the following steps outline the recommended method. For each of these steps, replace example.com with your domain name.
Create a copy of the default Apache configuration file for your site:
Open the new example.com configuration file in your text editor. Uncomment the ServerName option and update it with your domain. Enter the document root path and log directories as shown below, and add a Directory block before :
The ServerAlias directive allows you to include multiple domain names or subdomains for a single host. The example above allows visitors to use example.com or www.example.com to navigate to this virtual host.
Create the directories referenced above:
Assign ownership of public_html directory to the user www-data :
Set the permissions for the public_html directory:
Link your virtual host file from the sites-available directory to the sites-enabled directory:
Disable the default virtual host to minimize security risks:
Virtual hosting should now be enabled. To allow the virtual host to use your domain name, be sure that you have configured DNS services for your domain to point to your Linode’s IP address.
If there are additional websites you wish to host on your Linode, repeat the above steps to add a folder and configuration file for each.
MySQL
Log in to MySQL’s SQL shell:
You can keep using the auth_socket plugin, and this is considered a secure option for production systems. If you’d rather switch to password authentication and assign a password, enter the following commands. Replace password with a new root password:
By default, MySQL is configured to use the auth_socket authorization plugin. This authorization …
Exit the SQL shell:
Use the mysql_secure_installation tool to configure additional security options. This tool will ask if you want to set a new password for the MySQL root user, but you can skip that step:
Answer Y at the following prompts:
Edit the configuration file located in /etc/php/7.2/apache2/php.ini to enable more descriptive errors, logging, and better performance. The following modifications provide a good starting point:
Create the log directory for PHP and give ownership to the Apache system user:
Optional: Test and Troubleshoot the LAMP Stack
In this section, you’ll create a test page that shows whether Apache can render PHP and connect to the MySQL database. This can be helpful in locating the source of an error if one of the elements of your LAMP stack is not communicating with the others.
Navigate to example.com/phptest.php from your local machine. If the components of your LAMP stack are working correctly, the browser will display a “Connected successfully” message. If not, the output will be an error message.
Remove the test file:
Troubleshooting
If the site does not load at all, check if Apache is running, and restart it if required:
If the site loads, but the page returned is the default “Congratulations” page, return to the Configure Virtual Hosts section above and check that the DocumentRoot matches your example.com/public_html folder.
If the page returned says “Index of /” or has a similar folder tree structure, create a test index.html file or a test file as shown above.
Congratulations! You have now set up and configured a LAMP stack on Ubuntu 18.04 (LTS).
More Information
You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.
This page was originally published on Monday, June 4, 2018.
Источники информации:
- http://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-ubuntu-18-04
- http://losst.ru/ustanovka-lamp-ubuntu-18-04
- http://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu-20-04
- http://www.linode.com/docs/guides/how-to-install-a-lamp-stack-on-ubuntu-18-04/