介绍 (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.
“ LAMP”堆栈是一组开源软件,通常会安装在一起,以使服务器能够托管用PHP编写的动态网站和Web应用程序。 该术语是首字母缩写词,代表A pache Web服务器的L inux操作系统。 站点数据存储在M ySQL数据库中,动态内容由P HP处理。
In this guide, we’ll install a LAMP stack on an Ubuntu 20.04 server.
在本指南中,我们将在Ubuntu 20.04服务器上安装LAMP堆栈。
先决条件 (Prerequisites)
In order to complete this tutorial, you will need to have an Ubuntu 20.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 20.04.
为了完成本教程,您将需要有一台Ubuntu 20.04服务器,该服务器具有未启用root用户的sudo
用户帐户和基本防火墙。 可以使用我们针对Ubuntu 20.04的初始服务器设置指南进行配置。
第1步-安装Apache并更新防火墙 (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 default choice for hosting a website.
Apache Web服务器是世界上最受欢迎的Web服务器之一。 它有据可查,拥有活跃的用户社区,并且在Web的许多历史中已得到广泛使用,这使其成为托管网站的理想默认选择。
Install Apache using Ubuntu’s package manager, apt
:
使用Ubuntu的软件包管理器apt
安装Apache:
- sudo apt update sudo apt更新
- sudo apt install apache2 须藤apt install apache2
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
. You’ll also be prompted to confirm Apache’s installation by pressing Y
, then ENTER
.
如果这是您第一次在此会话中使用sudo
,则系统将提示您提供用户密码,以确认您具有使用apt
管理系统软件包的正确特权。 通过按Y
,然后按ENTER
,还将提示您确认Apache的安装。
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:
安装完成后,您需要调整防火墙设置以允许HTTP通信。 UFW具有不同的应用程序配置文件,您可以利用它们来完成此任务。 要列出所有当前可用的UFW应用程序配置文件,可以运行:
- sudo ufw app list sudo ufw应用程序列表
You’ll see output like this:
您将看到如下输出:
Output
Available applications:
Apache
Apache Full
Apache Secure
OpenSSH
Here’s what each of these profiles mean:
以下是每个配置文件的含义:
Apache: This profile opens only port
80
(normal, unencrypted web traffic).Apache :此配置文件仅打开端口
80
(正常的未加密Web流量)。Apache Full: This profile opens both port 80 (normal, unencrypted web traffic) and port 443 (TLS/SSL encrypted traffic).
Apache Full :此配置文件同时打开端口80(正常,未加密的网络流量)和端口443(TLS / SSL加密的流量)。
Apache Secure: This profile opens only port
443
(TLS/SSL encrypted traffic).Apache Secure :此配置文件仅打开端口
443
(TLS / SSL加密的流量)。
For now, it’s best to allow only connections on port 80
, since this is a fresh Apache installation and you still don’t have a TLS/SSL certificate configured to allow for HTTPS traffic on your server.
目前,最好只允许端口80
上的连接,因为这是全新的Apache安装,并且您仍未配置TLS / SSL证书以允许服务器上的HTTPS通信。
To only allow traffic on port 80
, use the Apache
profile:
要仅允许端口80
上的流量,请使用Apache
配置文件:
- sudo ufw allow in "Apache" sudo ufw在“ Apache”中允许
You can verify the change with:
您可以使用以下方法验证更改:
- sudo ufw status sudo ufw状态
Output
Status: active
To Action From
-- ------ ----
OpenSSH ALLOW Anywhere
Apache ALLOW Anywhere
OpenSSH (v6) ALLOW Anywhere (v6)
Apache (v6) ALLOW Anywhere (v6)
Traffic on port 80
is now allowed through the firewall.
现在允许通过防火墙的端口80
上的流量。
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):
您可以通过在Web浏览器中访问服务器的公共IP地址来立即进行抽查,以验证一切是否按计划进行(如果您没有此信息,请查看下一个标题下的注释,以了解您的公共IP地址是什么)。已经):
http://your_server_ip
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:
您将看到默认的Ubuntu 20.04 Apache网页,该网页用于提供信息和测试目的。 它看起来应该像这样:
If you see this page, then your web server is now correctly installed and accessible through your firewall.
如果您看到此页面,则您的Web服务器现在已正确安装并可以通过防火墙访问。
如何查找服务器的公共IP地址 (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.
如果您不知道服务器的公用IP地址是什么,可以通过多种方法找到它。 通常,这是您用于通过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:
从命令行有几种不同的方法可以做到这一点。 首先,您可以使用iproute2
工具通过键入以下命令来获取IP地址:
- ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//' ip addr显示eth0 | grep inet | awk'{print $ 2; }'| sed's /\/.*$//'
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:
一种替代方法是使用curl
实用程序与外部联系人联系,以告诉您它如何看待您的服务器。 通过询问特定的服务器您的IP地址是什么来完成此操作:
- curl http://icanhazip.com 卷曲http://icanhazip.com
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.
无论使用哪种方法获取IP地址,都请在Web浏览器的地址栏中键入它以查看默认的Apache页面。
第2步-安装MySQL (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.
现在,您已经启动并运行了Web服务器,您需要安装数据库系统,以便能够存储和管理站点数据。 MySQL是在PHP环境中使用的流行数据库管理系统。
Again, use apt
to acquire and install this software:
同样,使用apt
来获取并安装此软件:
- sudo apt install mysql-server sudo apt安装mysql服务器
When prompted, confirm installation by typing Y
, and then ENTER
.
出现提示时,请键入Y
,然后按ENTER
确认安装。
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:
安装完成后,建议您运行MySQL随附的安全脚本。 该脚本将删除一些不安全的默认设置,并锁定对数据库系统的访问。 通过运行以下命令来启动交互式脚本:
- sudo mysql_secure_installation 须藤mysql_secure_installation
This will ask if you want to configure the VALIDATE PASSWORD PLUGIN
.
这将询问您是否要配置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.
注意:启用此功能只是一个判断。 如果启用,与指定条件不匹配的密码将被MySQL拒绝并出现错误。 禁用验证是很安全的,但是您应该始终对数据库凭据使用强而独特的密码。
Answer Y
for yes, or anything else to continue without enabling.
答Y
(是),或其他任何继续不启用。
VALIDATE PASSWORD PLUGIN 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 plugin?
Press y|Y for Yes, any other key for No:
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.
如果回答“是”,则将要求您选择密码验证级别。 请记住,如果输入2
作为最强级别,则尝试设置任何不包含数字,大写,小写字母和特殊字符或基于常见词典单词的密码时,都会收到错误消息。
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: 1
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 dispenses the use of a password, even when one is set, you should define a strong password here as an additional safety measure. We’ll talk about this in a moment.
无论您是否选择设置VALIDATE PASSWORD PLUGIN
,服务器都将接下来要求您选择并确认MySQL 根用户的密码。 这不要与系统根目录混淆。 数据库根用户是对数据库系统具有完全特权的管理用户。 即使MySQL超级用户的默认身份验证方法免除了使用密码, 即使设置了密码,您也应在此处定义一个强密码作为附加的安全措施。 我们稍后再讨论。
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:
如果启用了密码验证,将显示您刚刚输入的根密码的密码强度,服务器将询问您是否要继续使用该密码。 如果您对当前密码感到满意,请在提示符下输入Y
代表“是”:
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.
对于其余的问题,请按Y
并在每个提示下按ENTER
键。 这将删除一些匿名用户和测试数据库,禁用远程root登录,并加载这些新规则,以便MySQL立即尊重您所做的更改。
When you’re finished, test if you’re able to log in to the MySQL console by typing:
完成后,通过键入以下内容来测试是否能够登录到MySQL控制台:
- sudo mysql 须藤MySQL
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:
这将以管理数据库用户root身份连接到MySQL服务器,这是通过在运行此命令时使用sudo
推断出来的。 您应该看到如下输出:
Output
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 22
Server version: 8.0.19-0ubuntu5 (Ubuntu)
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
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>
To exit the MySQL console, type:
要退出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 look like a security concern at first, 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
.
请注意,即使您在运行mysql_secure_installation
脚本时定义了一个密码,也不需要提供密码即可以root用户身份进行连接。 这是因为MySQL管理用户的默认身份验证方法是unix_socket
而不是password
。 即使最初看起来像是安全问题,它也使数据库服务器更加安全,因为唯一允许以root root用户身份登录的用户是具有sudo特权的系统用户,这些用户从控制台或通过以相同的特权。 实际上,这意味着您将无法使用管理数据库根用户从PHP应用程序进行连接。 在默认身份验证方法从unix_socket
更改为password
情况下,为MySQL 根帐户设置密码是一种保护措施。
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: At the time of this writing, the native MySQL PHP library mysqlnd
doesn’t support caching_sha2_authentication
, the default authentication method for MySQL 8. For that reason, when creating database users for PHP applications on MySQL 8, you’ll need to make sure they’re configured to use mysql_native_password
instead. We’ll demonstrate how to do that in Step 6.
注意:在撰写本文时,本机MySQL PHP库mysqlnd
不支持 caching_sha2_authentication
,这是MySQL 8的默认身份验证方法。因此,在MySQL 8上为PHP应用程序创建数据库用户时,您需要确保将它们配置为使用mysql_native_password
代替。 我们将在步骤6中演示如何做到这一点。
Your MySQL server is now installed and secured. Next, we’ll install PHP, the final component in the LAMP stack.
您MySQL服务器现已安装并保护。 接下来,我们将安装PHP,这是LAMP堆栈中的最后一个组件。
第3步-安装PHP (Step 3 — Installing PHP)
You have Apache installed to serve your content and MySQL installed to store and manage your data. PHP is the component of our setup that will process code to display dynamic content to the final user. In addition to the php
package, you’ll need php-mysql
, a PHP module that allows PHP to communicate with MySQL-based databases. You’ll also need libapache2-mod-php
to enable Apache to handle PHP files. Core PHP packages will automatically be installed as dependencies.
您已经安装了Apache以提供内容,并安装了MySQL以存储和管理数据。 PHP是我们安装程序的组件,它将处理代码以向最终用户显示动态内容。 除了php
软件包之外,您还需要php-mysql
,这是一个PHP模块,允许PHP与基于MySQL的数据库进行通信。 您还需要libapache2-mod-php
才能使Apache处理PHP文件。 核心PHP软件包将自动安装为依赖项。
To install these packages, run:
要安装这些软件包,请运行:
- sudo apt install php libapache2-mod-php php-mysql 须藤apt安装php libapache2-mod-php php-mysql
Once the installation is finished, you can run the following command to confirm your PHP version:
安装完成后,您可以运行以下命令来确认您PHP版本:
- php -v PHP -V
Output
PHP 7.4.3 (cli) (built: Mar 26 2020 20:24:23) ( 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
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.
至此,您的LAMP堆栈已完全可用,但是在可以使用PHP脚本测试设置之前,最好设置一个正确的Apache虚拟主机来保存您网站的文件和文件夹。 我们将在下一步中进行操作。
步骤4 —为您的网站创建虚拟主机 (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.
使用Apache Web服务器时,可以创建虚拟主机 (类似于Nginx中的服务器块)来封装配置详细信息,并在一台服务器中托管多个域。 在本指南中,我们将设置一个名为your_domain的域,但是您应该使用自己的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.
注意 :如果您使用DigitalOcean作为DNS托管服务提供商,则可以查看我们的产品文档,以获取有关如何设置新域名并将其指向服务器的详细说明。
Apache on Ubuntu 20.04 has one server block enabled by default that is configured to serve documents from the /var/www/html
directory. While this works well for a single site, it can become unwieldy if you are hosting multiple sites. Instead of modifying /var/www/html
, we’ll create a directory structure within /var/www
for the your_domain site, leaving /var/www/html
in place as the default directory to be served if a client request doesn’t match any other sites.
默认情况下,Ubuntu 20.04上的Apache启用了一个服务器块,该服务器块被配置为提供/var/www/html
目录中的文档。 尽管这对于单个站点非常有效,但是如果您托管多个站点,则可能变得笨拙。 我们将在/var/www
为your_domain网站创建目录结构,而不是修改/var/www/html
,如果客户请求未得到响应,则将/var/www/html
保留为要提供的默认目录匹配其他任何网站。
Create the directory for your_domain as follows:
为your_domain创建目录,如下所示:
sudo mkdir /var/www/your_domain
须藤mkdir / var / www / your_domain
Next, assign ownership of the directory with the $USER
environment variable, which will reference your current system user:
接下来,使用$USER
环境变量分配目录的所有权,该变量将引用您当前的系统用户:
sudo chown -R $USER:$USER /var/www/your_domain
须藤chown -R $ USER:$ USER / var / www / your_domain
Then, open a new configuration file in Apache’s sites-available
directory using your preferred command-line editor. Here, we’ll use nano
:
然后,使用首选的命令行编辑器在Apache的sites-available
目录中打开一个新的配置文件。 在这里,我们将使用nano
:
sudo nano /etc/apache2/sites-available/your_domain.conf
须藤纳米/ etc / apache2 / sites-available / your_domain .conf
This will create a new blank file. Paste in the following bare-bones configuration:
这将创建一个新的空白文件。 粘贴以下基本配置:
<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
, you can do that by pressing CTRL+X
, then Y
and ENTER
.
完成后,保存并关闭文件。 如果您使用的是nano
,则可以按CTRL+X
,然后按Y
和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 #
character in the beginning of each option’s lines.
通过此VirtualHost
配置,我们告诉Apache使用/var/www/ your_domain
作为Web根目录来服务your_domain
。 如果要测试不带域名的Apache,则可以通过在每个选项行的开头添加#
字符来删除或注释掉ServerName
和ServerAlias
选项。
You can now use a2ensite
to enable the new virtual host:
现在,您可以使用a2ensite
启用新的虚拟主机:
sudo a2ensite your_domain
须藤a2ensite your_domain
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:
您可能要禁用Apache随附的默认网站。 如果您不使用自定义域名,则需要这样做,因为在这种情况下,Apache的默认配置将覆盖您的虚拟主机。 要禁用Apache的默认网站,请输入:
- sudo a2dissite 000-default 须藤a2dissite 000-默认
To make sure your configuration file doesn’t contain syntax errors, run:
要确保您的配置文件不包含语法错误,请运行:
- sudo apache2ctl configtest 须藤apache2ctl configtest
Finally, reload Apache so these changes take effect:
最后,重新加载Apache,以使这些更改生效:
- sudo systemctl reload apache2 sudo systemctl重新加载apache2
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:
您的新网站现在处于活动状态,但是Web根目录/var/www/ your_domain
仍然为空。 在该位置创建一个index.html
文件,以便我们可以测试虚拟主机是否按预期工作:
nano /var/www/your_domain/index.html
纳米/ var / www / your_domain /index.html
Include the following content in this file:
在此文件中包括以下内容:
<html>
<head>
<title>your_domain website</title>
</head>
<body>
<h1>Hello World!</h1>
<p>This is the landing page of <strong>your_domain</strong>.</p>
</body>
</html>
Now go to your browser and access your server’s domain name or IP address once again:
现在转到浏览器,再次访问服务器的域名或IP地址:
http://server_domain_or_IP
You’ll see a page like this:
您会看到这样的页面:
If you see this page, it means your Apache virtual host is working as expected.
如果看到此页面,则表明您的Apache虚拟主机正在按预期运行。
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.
您可以将该文件保留为应用程序的临时登录页面,直到您设置一个index.php
文件来替换它为止。 完成此操作后,请记住从文档根目录中删除或重命名index.html
文件,因为默认情况下它将优先于index.php
文件。
关于Apache上DirectoryIndex
的注释 (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.
使用Apache上的默认DirectoryIndex
设置,名为index.html
的文件将始终优先于index.php
文件。 通过创建一个临时的index.html
文件,其中包含向访问者提供的信息,这对于在PHP应用程序中设置维护页面很有用。 由于此页面将优先于index.php
页面,因此它将成为该应用程序的登录页面。 维护结束后,将index.html
重命名或从文档根目录中删除,从而返回常规应用程序页面。
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:
如果要更改此行为,则需要编辑/etc/apache2/mods-enabled/dir.conf
文件,并修改DirectoryIndex
指令中index.php
文件的列出顺序:
- sudo nano /etc/apache2/mods-enabled/dir.conf 须藤纳米/etc/apache2/mods-enabled/dir.conf
<IfModule mod_dir.c>
DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>
After saving and closing the file, you’ll need to reload Apache so the changes take effect:
保存并关闭文件后,您需要重新加载Apache,以使更改生效:
- sudo systemctl reload apache2 sudo systemctl重新加载apache2
In the next step, we’ll create a PHP script to test that PHP is correctly installed and configured on your server.
在下一步中,我们将创建一个PHP脚本来测试您的服务器上是否已正确安装和配置PHP。
第5步-在Web服务器上测试PHP处理 (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.
现在您已经有了一个自定义位置来托管您网站的文件和文件夹,我们将创建一个PHP测试脚本来确认Apache能够处理和处理对PHP文件的请求。
Create a new file named info.php
inside your custom web root folder:
在自定义Web根文件夹中创建一个名为info.php
的新文件:
nano /var/www/your_domain/info.php
纳米/ var / www / your_domain /info.php
This will open a blank file. Add the following text, which is valid PHP code, inside the file:
这将打开一个空白文件。 在文件内添加以下文本,这是有效PHP代码:
<?php
phpinfo();
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
:
要测试此脚本,请转到Web浏览器并访问服务器的域名或IP地址,然后访问脚本名称(在本例中为info.php
:
http://server_domain_or_IP/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.
该页面从PHP的角度提供有关服务器的信息。 这对于调试和确保正确应用设置很有用。
If you can see this page in your browser, then your PHP installation is working as expected.
如果您可以在浏览器中看到此页面,则说明您PHP安装已按预期进行。
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:
在通过该页面检查有关PHP服务器的相关信息之后,最好删除您创建的文件,因为该文件包含有关PHP环境以及Ubuntu服务器的敏感信息。 您可以使用rm
来这样做:
sudo rm /var/www/your_domain/info.php
须藤rm / var / www / your_domain /info.php
You can always recreate this page if you need to access the information again later.
如果以后需要再次访问该信息,则始终可以重新创建此页面。
第6步-从PHP测试数据库连接(可选) (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.
如果要测试PHP是否能够连接到MySQL并执行数据库查询,则可以创建带有伪数据的测试表,并从PHP脚本中查询其内容。 在此之前,我们需要创建一个测试数据库和一个正确配置为可以访问它的新MySQL用户。
At the time of this writing, the native MySQL PHP library mysqlnd
doesn’t support caching_sha2_authentication
, the default authentication method for MySQL 8. We’ll need to create a new user with the mysql_native_password
authentication method in order to be able to connect to the MySQL database from PHP.
在撰写本文时,本机MySQL PHP库mysqlnd
不支持 caching_sha2_authentication
,这是MySQL 8的默认身份验证方法。我们需要使用mysql_native_password
身份验证方法创建一个新用户,以便能够连接到PHPMySQL数据库。
We’ll create a database named example_database and a user named example_user, but you can replace these names with different values.
我们将创建一个名为example_database数据库和用户名为example_user,但你可以用不同的值替换这些名称。
First, connect to the MySQL console using the root account:
首先,使用root帐户连接到MySQL控制台:
- sudo mysql 须藤MySQL
To create a new database, run the following command from your MySQL console:
要创建新数据库,请从MySQL控制台运行以下命令:
CREATE DATABASE example_database;
创建数据库example_database ;
Now you can create a new user and grant them full privileges on the custom database you’ve just created.
现在,您可以创建一个新用户,并向他们授予您刚创建的自定义数据库的全部特权。
The following command creates a new user named example_user
, using mysql_native_password
as default authentication method. We’re defining this user’s password as password
, but you should replace this value with a secure password of your own choosing.
以下命令使用mysql_native_password
作为默认身份验证方法创建一个名为example_user
的新用户。 我们将此用户的密码定义为password
,但是您应使用自己选择的安全密码替换此值。
CREATE USER 'example_user'@'%' IDENTIFIED WITH mysql_native_password BY 'password';
创建用户' example_user '@'%'用mysql_native_password标识' 密码 ';
Now we need to give this user permission over the example_database
database:
现在,我们需要授予该用户对example_database
数据库的权限:
- GRANT ALL ON example_database.* TO 'example_user'@'%'; 全部授予example_database。* TO'example_user'@'%';
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.
这将为example_user用户提供对example_database数据库的完全特权,同时阻止该用户在服务器上创建或修改其他数据库。
Now exit the MySQL shell with:
现在使用以下命令退出MySQL Shell:
- exit 出口
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:
您可以使用自定义用户凭据再次登录到MySQL控制台,以测试新用户是否具有适当的权限:
mysql -u example_user -p
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:
请注意此命令中的-p
标志,它将提示您输入创建example_user用户时使用的密码。 登录到MySQL控制台后,确认您有权访问example_database数据库:
- SHOW DATABASES; 显示数据库;
This will give you the following output:
这将为您提供以下输出:
Output
+--------------------+
| Database |
+--------------------+
| example_database |
| information_schema |
+--------------------+
2 rows in set (0.000 sec)
Next, we’ll create a test table named todo_list. From the MySQL console, run the following statement:
接下来,我们将创建一个名为todo_list的测试表。 在MySQL控制台中,运行以下语句:
CREATE TABLE example_database.todo_list (
创建表example_database 。 todo_list (
- item_id INT AUTO_INCREMENT, item_id INT AUTO_INCREMENT,
- content VARCHAR(255), 内容VARCHAR(255),
- PRIMARY KEY(item_id) 主键(item_id)
- ); );
Insert a few rows of content in the test table. You might want to repeat the next command a few times, using different values:
在测试表中插入几行内容。 您可能需要使用不同的值重复执行下一条命令几次:
INSERT INTO example_database.todo_list (content) VALUES ("My first important item");
插入INTO example_database 。 todo_list (内容)VALUES(“ 我的第一个重要项目 ”);
To confirm that the data was successfully saved to your table, run:
要确认数据已成功保存到表中,请运行:
SELECT * FROM example_database.todo_list;
SELECT * FROM example_database 。 todo_list ;
You’ll see the following output:
您将看到以下输出:
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, you can exit the MySQL console:
确认测试表中有有效数据后,可以退出MySQL控制台:
- 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. We’ll use nano
for that:
现在,您可以创建将连接到MySQL并查询您的内容PHP脚本。 使用首选编辑器在自定义Web根目录中创建一个新PHP文件。 我们将为此使用nano
:
nano /var/www/your_domain/todo_list.php
纳米/ 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. Copy this content into your todo_list.php
script:
以下PHP脚本连接到MySQL数据库,并查询todo_list表的内容,并将结果显示在列表中。 如果数据库连接有问题,它将引发异常。 将此内容复制到您的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
:
现在,您可以在Web浏览器中访问此页面,方法是访问为网站配置的域名或公共IP地址,然后访问/todo_list.php
:
http://your_domain_or_IP/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.
这意味着您PHP环境已准备就绪,可以连接到MySQL服务器并与之交互。
结论 (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.
在本指南中,我们使用Apache作为Web服务器,使用MySQL作为数据库系统,为为访问者提供PHP网站和应用程序奠定了灵活的基础。
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.
下一步,您应该通过HTTPS为您的Web服务器提供安全的连接,以确保安全。 为此,您可以使用“ 让我们加密”来使用免费的TLS / SSL证书来保护您的网站。