Appunti di Programmazione

Mint 20: Installiamo Apache, MySQL e PHP (LAMP)

Da un pò di tempo utilizzo PHP e MySQL su server Apache per la realizzazione di alcuni programmi e pagine web a me necessari, pertanto, essendo passato recentemente a Linux Mint 20, ho dovuto ricreare un ambiente di sviluppo adatto allo scopo. Vediamo come.

[1] - Per prima cosa puliamo la cache locale dei pacchetti:

$ sudo apt-get clean

[2] - Quindi scarichiamo la lista aggiornata dei pacchetti stessi:

$ sudo apt-get update

[3] - Infine installiamoli:

$ sudo apt-get upgrade

Installiamo Apache

[4] - Installiamo 'apache2'

$ sudo apt install apache2

Se tutto si è svolto in modo corretto e senza errori, digitando nel browser "http://localhost" oppure "http://127.0.0.1" appare la seguente pagina:

Pagina di corretto avvio di Apache 2

[5] - Si può controllare se il server Apache è attivo anche digitando il seguente comando nel terminale:

$ systemctl status apache2
● apache2.service - The Apache HTTP Server
     Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor prese>
     Active: active (running) since Wed 2022-11-02 09:38:30 CET; 27s ago
       Docs: https://httpd.apache.org/docs/2.4/
    Process: 6873 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SU>
   Main PID: 6890 (apache2)
      Tasks: 12 (limit: 9216)
     Memory: 13.5M
     CGroup: /system.slice/apache2.service
             ├─6890 /usr/sbin/apache2 -k start
             ├─6891 /usr/sbin/apache2 -k start
             ├─6892 /usr/sbin/apache2 -k start
             ├─6894 /usr/sbin/apache2 -k start
             ├─6895 /usr/sbin/apache2 -k start
             ├─7212 /usr/sbin/apache2 -k start
             ├─7213 /usr/sbin/apache2 -k start
             ├─7214 /usr/sbin/apache2 -k start
             ├─7215 /usr/sbin/apache2 -k start
             ├─7216 /usr/sbin/apache2 -k start
             └─7217 /usr/sbin/apache2 -k start

nov 02 09:38:29 gandalfrank systemd[1]: Starting The Apache HTTP Server...
nov 02 09:38:30 gandalfrank apachectl[6883]: AH00558: apache2: Could not reli>

dove la voce "Active: active (running)..." indica chiaramente che il server è in funzione."

Ecco quattro comandi per la gestione del server:

  • systemctl status apache2 - Mostra lo stato del server.
  • systemctl start apache2 - Avvia il server.
  • systemctl restart apache2 - Forza il riavvio del server.
  • systemctl stop apache2 - Arresta il server.

La directory nella quale inserire i nostri file .html e .php, che devono essere interpretati dal server, è la seguente: /var/www/html/ .

Installiamo MySQL

[6] - Installiamo 'mysql-server'

$ sudo apt install mysql-server

[7] - Verifichiamo che funzioni correttamente effettuando l'accesso in questo modo:

$ sudo mysql
[sudo] password di gandalfrank:
Welcome to the mysql monitor.  Commands end with ; or \g.
Your mysql connection id is 11
Server version: 8.0.31-0ubuntu0.20.04.2 (Ubuntu)

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

[8] - OPPURE in quest'altro modo effettuando il login direttamente come root:

$ su
Password: 

[8.a] - Quindi:

# mysql
Welcome to the mysql monitor.  Commands end with ; or \g.
Your mysql connection id is 11
Server version: 8.0.31-0ubuntu0.20.04.2 (Ubuntu)

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Considetato che non ci sono errori e che il prompt 'mysql>' è ben visibile, significa che siamo riusciti a connettersci alla shell e che l'installazione è andata a buon fine. Come avrete notato non è stato necessario inserire password per avere accesso a MySQL, poiché automaticamente durante l'installazione, è stato impostato un solo utente, l'amministratore, detto anche root, per il quale non è stata prevista, almeno per adesso, nessuna parola d'ordine, mancanza alla quale provvederemo immediatamente.

[9] - Usciamo dalla shell di MySQL:

mysql> quit;

Per impostare un buon livello di sicurezza del nostro DBMS (DataBase Management System) MySQL, la stessa casa produttrice ha previsto uno script con cui scegliere una password per l'amministratore e attivare alcune opzioni per rendere più sicuro l'accesso ai soli utenti abilitati: mysql_secure_installation.

[10] - Avviamo lo script.

$ sudo mysql_secure_installation
[sudo] password di gandalfrank:

[11] - Verrà chiesto di installare il componente per la validazione della password, scegliete 'y' (yes).

VALIDATE PASSWORD COMPONENT can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD component?

Press y|Y for Yes, any other key for No: y

[12] - A questo punto va scelto il livello di sicurezza da impostrare per la definizione della password.

There are three levels of password validation policy:

LOW    Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary                  file

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 2
Please set the password for root here.

[13] - Inserite la nuova parola di accesso per l'utente root 2 volte e se tutto va bene digitate 'y' (yes) alla domanda di proseguire con la password appena inserita.

New password: 

Re-enter new password: 

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

***ATTENZIONE!!!*** Se tutto è andato bene passate direttamente al punto [14] - , altrimenti se appare il messaggio di errore sottostante proseguite nella lettura.

 ... 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

[13.a] - Avviate una nuova finestra del terminale e 'uccidete' il processo di 'mysql_secure_installation' in questo modo:

$ sudo killall -9 mysql_secure_installation
[sudo] password di gandalfrank:

[13.b] - Riavviate MySQL.

$ sudo mysql

[13.c] - Impartite questo comando:

mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'NuovaPassword';
Query OK, 0 rows affected (0,01 sec)

'NuovaPassword' è ovviamente la vostra nuova parola d'ordine che dovete impopstare.

[13.d] - Uscite.

mysql> exit
Bye

[13.e] - Riavviate lo 'script mysql_sedcure_installation' inserendo, quando richiesto, la 'NuovaPassword'.

$ sudo mysql_secure_installation

Securing the mysql server deployment.

Enter password for user root: 
The 'validate_password' component is installed on the server.
The subsequent steps will run with the existing configuration
of the component.
Using existing password for root.

Estimated strength of the password: 100 
Change the password for root ? ((Press y|Y for Yes, any other key for No) : n
...

[14] - Proseguite con il rispondere 'y' (yes) a tutte le domande successive per impostare un ottimo livello di sicurezza per il vostro mysql-server

By default, a mysql installation has an anonymous user,
allowing anyone to log into mysql without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.

Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
Success.


Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y
Success.

By default, mysql comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.


Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y
 - Dropping test database...
Success.

 - Removing privileges on test database...
Success.

Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y
Success.

All done!

[15] - A questo punto, da terminale, per avere accesso come root a MySQL è necessario eseguire il seguente comando:

$ mysql -u root -p
Enter password: 
Welcome to the mysql monitor.  Commands end with ; or \g.
Your mysql connection id is 31
Server version: 8.0.31-0ubuntu0.20.04.2 (Ubuntu)

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

[16] - Personalmente preferisco NON usare l'utente root per la manipolazione dei dati del database, ma utilizzare un account normale creato ad hoc per questo scopo.
Creaiamo, a titolo di esempio, un utente di nome 'pippo' e con password 'Pippo@123', per avere accesso a tutti i database con ogni privilegio. Tale utente viene memorizzato automaticamente nella tabella 'user' del database 'MySQL'.

mysql> CREATE USER 'pippo'@'localhost' IDENTIFIED by 'Pippo@123';
Query OK, 0 rows affected (0,01 sec)

[17] - Assegnamo tutti i privilegi al nuovo utente:

mysql> GRANT ALL PRIVILEGES ON *.* TO 'pippo'@'localhost';
Query OK, 0 rows affected (0,01 sec)

Qualora appaia un messaggio di errore nell'assegnazione dei privilegi per il nuovo utente, dovrebbe essere sufficiente chiudere MySQL, uscire dal terminale e loggarsi di nuovo con le stesse credenziali usate in precedenza, quindi riprovare ad eseguire il comando.

[18] - Se tutto è andato bene aggiorniamo la tabella dei privilegi degli utenti.

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0,00 sec)

A questo punto possiamo iniziare a lavorare.
I DB creati sono contenuti nella cartella /var/lib/mysql e i file di configurazione in /etc/mysql

[19] - Per entrare in MySQL si può usare sia l'utente root:.

$ mysql -u root -p
Enter password:

OPPURE l'utente 'pippo' appena creato:

$ mysql -u pippo -p
Enter password:

Installiamo PHP

[20] - Installiamo PHP e alcune sue librerie.

$ sudo apt install php libapache2-mod-php php-mysql

[21] - Controlliamo se PHP è stato installato:

$ php -v
PHP 7.4.3 (cli) (built: Aug 17 2022 13:29:56) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.3, Copyright (c), by Zend Technologies