9 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Apache NetBeans 12. 5

Настройка среды разработки PHP в Linux Ubuntu

В данном учебном курсе рассматривается процедура настройки среды разработки PHP в операционной системе Ubuntu (версия 7.10 и более поздние). Эта процедура предполагает установку и настройку механизма PHP, базы данных MySQL, веб-сервера Apache и отладчика XDebug.

Для работы с этим учебным курсом требуется следующее программное обеспечение и ресурсы.

Пакет загрузки PHP

Рекомендуется использовать HTTP-сервер Apache 2.2.

Сервер базы данных

Рекомендуется использовать сервер MySQL 5.0.

Отладчик PHP (не обязательно)

Версия XDebug 2.0 или более поздняя

Как правило, разработка и отладка выполняются на локальном веб-сервере, в то время как производственная среда размещена на удаленном веб-сервере. Настройка удаленного веб-сервера описана в разделе + Развертывание приложения PHP на удаленном веб-сервере с помощью IDE NetBeans+. Этот учебный курс содержит информацию, необходимую для настройки локального веб-сервера. Поддержка PHP может добавляться к целому ряду локальных веб-серверов (IIS, Xitami и т.д.), но обычно используется сервер HTTP Apache.

By default, the PhpMyAdmin package is included in the Ubuntu 20.04 default repository. You can install it using the following command:

During the installation, you will be asked to select a web server to configure as shown below:

Select Web Server

Select apache2 as a webserver and click on the Ok button. You will be asked to configure a database for phpMyAdmin with dbconfig-common as shown below:

Configure Database

Select Yes and hit Enter. You will be asked to set a password for the phpmyadmin user in MariaDB as shown below:

Set Password

Provide your desired password and hit Enter to start the installation.

Once the installation is completed, a new database and a user named phpmyadmin are created with all necessary privileges to manage this database.

To check the privileges, connect to the MariaDB with the following command:

Once connected, check the privileges using the following command:

You should get the following output:

Next, exit from the MariaDB with the following command:

How To Install LAMP Stack and PhpMyAdmin (Ubuntu 20.04)

In this tutorial, we are going to discuss how to install LAMP stack with PhpMyAdmin on Ubuntu 20.04 server/desktop. Lamp stack here actually means a combination of software packages which are mostly used to create a dynamic website. The popular software packages to create a LEMP stack includes Linux, Apache, MySQL/MariaDB and PHP. Also, we will discuss to install PhpMyAdmin with LAMP stack so the users can access and manage their databases through web interface.

So, let’s begin with the prerequisites which is necessary before we proceed to install LAMP stack and PhpMyAdmin on Ubuntu 20.04

Prerequsites

  • Ubuntu 20.04 server
  • Superuser ( sudo ) enabled user account

Detailed steps to install LAMP and PhpMyAdmin On Ubuntu 20.04

We hope you might have access to Ubuntu server with a sudo enabled user as mentioned in the prerequisites. If yes, proceed with steps in order to install LAMP Stack and configure the software packages to host any of your websites.

Читайте так же:
7-PDF Maker 1.5.2

Table of Contents

Step 1: Install Apache and configure Firewall (UFW)

The very first essential software package to build a LAMP stack is Apache. This is the most popular web server package that is widely used globally, and is also considered as the best choice to host websites. In order to install Apache on Ubuntu server, we will use default package manager in this operating system called apt.

here’s the command to install Apache.

When the second command is executed to install Apache, it will ask you to confirm the installation process. Just press y and hit Enter key.

In order to allow HTTP traffic on your web server, it’s necessary allow the traffic in (UFW) firewall settings in Ubuntu. So, check the currently available UFW application profiles on your server with the command below:

Note: Run the first command if this is your first session with Ubuntu 20.04 as the UFW firewall is disabled by default. So, it’s necessary to enable it first to check the available application profile list.

Here’s the output you will see on screen:

Since this is your first session while configuring Apache, it’s best suggested to allow connections only through port 80 . the other options will be required to be enabled if you install SSL/TLS certificate which uses HTTPS protocol to run.

So, just allow traffic on port 80 , and thus we will use Apache profile from the list shown above:

In order to test the changes in UFW, check the status now:

and here’s the output you can expect to see on screen.

The output as shown above confirms that port 80 on your Ubuntu server is now ready to get traffic. You can also check the same by visiting your public IP address assigned to your server. Just type the IP in browser.

If all settings are right as configured above, you can see default Apache web page on browser like one shown in the image below.

Apache 2 ubuntu default page

Note: If you are not aware of your server’s IP address to check the configuration done in above steps, you can run ‘ curl http://icanhazip.com ’ command in command line. The utility named curl actually connects to an third party to ask your server’s IP, and it will display the address on screen.

Step 2: Install and secure MySQL server

After installing Apache, the second essential software package to build LAMP stack is MySQL/MariaDB server. In out tutorial, we are going to install and secure MySQL as it’s a very popular and widely used database management system.

So, in order to install MySQL on Ubuntu, run the command below using apt :

Running the command above will ask you to confirm the installation. Just press y and hit Enter key.

Читайте так же:
Драйвера для веб камеры A4Tech

Now, it’s suggested to secure your MySQL installation. Secure, means to remove some default insecure settings from the database management server. This is basically done by running a security script which comes pre-installed with MySQL.

In order to execute the preinstalled MySQL security script, run the command here:

Doing this will ask you to configure the VALIDATE PASSWORD PLUGIN. This is necessary to make sure if your MySQL will reject any query to access the databases unless a matched password is entered. In order to do so, we suggest to use a strong and unique password.

So, press y and hit Enter key. You can also press other keys if you wish not to secure your MySQL with password. Here’s the output you will receive on screen:

There are three levels of password validation policy:

You will be asked to select a level of password validation. Since it’s recommended to keep a strongest password level always for your MySQL root user, you should select 2 in the provided option. Once you enter the answer, you will next be asked to enter a strong password, and re-enter the same to confirm the password for MySQL root user.

Since you enabled the password validation plugin for MySQL, you will be shown with the password strength as well to meet your desired answer ( 2 = Strong ). If the plugin finds your password as weak, it will show the less estimated strength value. In such case, you need to try entering another strong password. Once you confirm the password is strong enough to keep, you can enter y as answer when prompted.

Here’s the output you will receive on screen.

In the next step, you will be asked to Remove anonymous users, Disallow root login remotely, Remove test database and access to it, and Reload privileges tables now. Just keep answering them by hitting y.

Doing all above steps, you have successfully secured your MySQL server. Now, you can log in to MySQL console by entering the command below:

The command will connect MySQL server as root user and the console will be shown on screen like this:

Here, you can enter your queries to create database, users, and manage the databases according to your needs. For more information on how to access MySQL databases, users and managing them, read our previous article.

To close the MySQL console, just enter the command below:

Note: Although, you have set a password to connect to root users, but you are not asked to enter the password above because the default authentication method for administrative MySQL user ( root ) is Unix_socket . However, when it’s tried use administrative database root user with PHP application, it will fail. For security reasons, it’s highly suggested to create a dedicated user accounts with limited privileges for every database. We will discuss how to configure mysql_native_password for database users in the steps further.

Step 3: Install PHP

In the LAMP stack, the third essential component is PHP. This component is actually used to process code to show up dynamic content to users. So, in this step, we are going to discuss how to install PHP packages now. In addition, we will also install php-mysql , a specific PHP module which is essential to allow PHP communicating with MySQL databases. Even libapache2-mod.php is required to enable Apache to handle PHP files as well.

Читайте так же:
Как Изменить Язык в Вайбере На Компьютере

All above can be installed easily with a single command as mentioned:

After the installation is finished, you can run “ php -v ” command to view your PHP version. At the time or writing this article, the default PHP version was noticed as 7.4.3. here’s what the output we received:

So, with this step, the you have learned how to install LAMP stack on Ubuntu 20.04. In the next steps, we will discuss how to setup Apache Virtual Host which technically hold website’s files and folders. Also, we will test a PHP script to check our installed LAMP setup if it’s working fine.

Step 4: Create Virtual Host for your domain (servonode.com is taken here as example)

While we have installed LAMP stack, you will need to create virtual hosts either to host a single domain or more than once from a single server. We suggest you to replace servonode.com with your own domain where it’s highlighted in the instructions below.

Although, the default server block with Apache on Ubuntu 20.04 is configured to server documents from /var/www/html directory, and it can easily be used to serve a single domain, still using the same to server multiple domains can be weird. So, it’s better to create a new virtual host with root directory pointing to /var/www for your domain or domains.

At first, we need to create a directory for your domain in the aforementioned directory with the command below:

Change the directory ownership with $USER , that basically indicates to current system user. You can do this with following command:

Once done, you can create/open a new virtual host file for your domain in Apache’s sites-available directory using nano text editor:

Now, just copy and paste the following code into the blank file, don’t forget to change the domain name and document root directory locations as we set in the steps above.

Press CTRL+S to save the document, followed by Pressing CTRL+X then y then Enter key, to exit the document editor.

Note: In the created virtual host file, we have configured Apache to server servonode.com from /var/www/servonode.com as root directory.

Now, run the command below to enable newly created virtual host for domain, and disable the default virtual host file installed with Apache.

Читайте так же:
5 лучших программ для быстрых скриншотов

After this, you can verify the configuration file for any errors with following command:

In case, if you see any error on screen, there might be some issue with your virtual host configuration file. To resolve, check your configuration again to fix the issues. Once done, you should reload Apache to load the changes in effect.

So, your domain is now active and ready to server contents from assigned web root directory. Since, the root directory is still empty, when you open your domain on browser, it will show you nothing. In order to test your site, we suggest you to create a demo PHP file in the directory with command below.

Just copy and paste the code below in the file, then save and exit it.

Now, open your browser and enter your domain name and it will show you PHP information as shown in the image below.

php info page

Step 5: Install PhpMyAdmin

Although, PhpMyAdmin is not a part of LAMP stack, still while configuring a dynamic website on LAMP, a user might need to administer MySQL/MariaDB databases through web interface. So, we have included the instructions to install PhpMyAdmin in this tutorial as well.

In order to install PhpMyAdmin on Ubuntu 20.04, run the command:

Once the installation runs, you may asked to confirm installation, just press y and hit Enter . During the installation, you will also be asked to choose preferred web server that should be automatically configured to run PhpMyAdmin. Since we have configured LAMP, select Apache as your option, and press Enter .

After the selection of preferred web server, PhpMyAdmin also must have a database installed and configured before it can work. To do so, select yes as option when you are asked “ Configure database for phpmyadmin with dbconfig-common. ”

Next is to create a password to register MySQL database server. You can use the same password as well which you have configured for your MySQL root user in above steps.

After successful installation is complete, the configuration files of PhpMyAdmin can be located within /etc/phpmyadmin , while the main files are located within /etc/phpmyadmin/config.inc.php . Also an essential file is saved within /etc/phpmyadmin/apache.conf that allows Apache to work with PhpMyAdmin. So, obviously we need not to configure Apache2 to serve PhpMyAdmin site.

To do aforementioned task, run the command below to create symbolic link between /etc/phpmyadmin/apache.conf to /etc/apache2/conf-available/phpmyadmin.conf . After this, the next commands are to enable phpmyadmin.conf files for Apache2 and restart Apache2 services.

Now, open your browser and browse http://servonode.com/phpmyadmin to open phpmyadmin web interface. After the page loads on screen, you can enter the dashboard of phpmyadmin by entering root as username and assigned password.

So, we have successfully learned how to install LAMP stack and PhpMyadmin on Ubuntu 20.04. in case you find any issue while following our steps, or find some errors, let us know through Suggest Us page or comment below.

Читайте так же:
Как в Автокаде сохранить в JPEG?

4. Obscure phpMyAdmin URL

Bots continuously scan web servers for the default phpMyAdmin login page, so it is recommended that you change the URL to something else.

In this example we are going to change it from example.com/phpmyadmin to example.com/pmahidden .

Open the phpMyAdmin configuration file for Apache using the nano text editor.

Change the Alias from /phpmyadmin to /pmahidden – you can change this to whatever you want.

Save and exit (press CTRL + X , press Y and then press ENTER )

Now you must reload the Apache service for changes to take effect.

You should now be able to access phpMyAdmin at example.com/pmahidden

Настройка Apache (необязательно)

Теперь, когда у вас есть Apache, обслуживающий веб-страницы на вашем Ubuntu 20.04, могут потребоваться дополнительные настройки конфигурации.

Отключить список каталогов и включить AllowOverride

Apache по умолчанию будет перечислять содержимое ваших каталогов без индексов (index.html, index.РНР). Это угроза безопасности, поскольку она позволяет хакерам просматривать ваш веб-сервер в поисках сценариев.

Вы также обнаружите, что .htaccess по умолчанию в Apache будет игнорироваться. Если понадобится .htaccess, вы можете включить его, изменив файл конфигурации Apache.

Откройте файл конфигурации:

Нажмите CTRL + W и найдите <Directory /var/www/>.

Блок должен выглядеть примерно так:

Удалите Indexes, чтобы остановить список каталогов Apache, и измените AllowOverride None на AllowOverride All, чтобы включить .htaccess. Теперь это должно выглядеть так:

Сохраняем и выходим (CTRL+X, Y, ENTER).

Далее перезапускаем Apache.

Включить mod_rewrite

Если вы хотите настроить некоторые правила .htaccess, вам, скорее всего, придется включить mod_rewrite.

Далее нужно перезапустить Apache.

На этом полная установка и настройка стека LAMP завершена.

В скором времени ждите материал по установке phpMyAdmin. Всех с наступающим!

Установка MySQL на Ubuntu 20.04

Во время исполнения второй команды, на все запросы подтверждать (Yes).

Устанавливается MySQL 8, в этой версии есть особенность — изменен плагин авторизации, по умолчанию. Из-за этого, старые CMS могут давать ошибку при соединении с сервером MySQL.

Для исправления такой ошибки нужно создавать пользователей с опцией "mysql_native_password":

Также нужно изменить файл /etc/mysql/mysql.conf.d/mysqld.cnf, добавить туда строку, в секцию [mysqld]:

Once phpMyAdmin is installed you can configure it with Apache so you can access the web interface.

Copy the phpmyadmin.conf from our installation to Apache’s conf-available directory.

Enable the configuration using a2enconf command.

Restart Apache for the changes to take effect.

Now you can access phpMyAdmin using your domain followed by /phpmyadmin .

Conclusion

Now you have learned how to install phpMyadmin on Ubuntu 20.04 with Apache.

Thanks for your time. If you face any problem or any feedback, please leave a comment below.

Cloudbooklet builds a large collection of Linux based guides and tutorials on Cloud platforms like Google Cloud, AWS, Azure, DigitalOcean and more

голоса
Рейтинг статьи
Ссылка на основную публикацию
ВсеИнструменты
Adblock
detector