CentOS 7上yum安裝實現LAMP環境

一、實驗環境

CentOS環境:
[root@localhost ~]# cat /etc/redhat-release 
CentOS Linux release 7.1.1503 (Core) 
[root@localhost ~]# uname -a
Linux localhost.localdomain 3.10.0-229.el7.x86_64 #1 SMP Fri Mar 6 11:36:42 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
[root@localhost ~]# ip addr show|sed -rn '/inet[[:space:]]+127/! s/^[[:space:]]+inet[[:space:]]+(.*)\/[[:digit:]]+[[:space:]]+.*$/\1/p'
172.16.0.77

Selinux關閉狀態,firewalld防火牆啓動狀態。
使用默認的base倉庫以及配置了epel倉庫。

二、yum安裝httpd2.4並簡單配置和說明

2.1、yum安裝httpd2.4

直接在bash接口執行安裝:
[root@localhost ~]# yum install httpd
...... #安裝過程省略。

默認的httpd的版本:
[root@localhost ~]# httpd -v
Server version: Apache/2.4.6 (CentOS)
Server built:   Nov  5 2018 01:47:09

httpd:apache的httpd項目。The apache httpd服務器是功能強大的,高效的而且可擴展的web服務器。
[root@localhost ~]# rpm -qi httpd
Name        : httpd
Version     : 2.4.6
Release     : 88.el7.centos
Architecture: x86_64
Install Date: Fri 21 Dec 2018 08:39:35 PM CST
Group       : System Environment/Daemons
Size        : 9817309
License     : ASL 2.0
Signature   : RSA/SHA256, Mon 12 Nov 2018 10:28:53 PM CST, Key ID 24c6a8a7f4a80eb5
Source RPM  : httpd-2.4.6-88.el7.centos.src.rpm
Build Date  : Mon 05 Nov 2018 09:48:57 AM CST
Build Host  : x86-01.bsys.centos.org
Relocations : (not relocatable)
Packager    : CentOS BuildSystem <http://bugs.centos.org>
Vendor      : CentOS
URL         : http://httpd.apache.org/
Summary     : Apache HTTP Server
Description :
The Apache HTTP Server is a powerful, efficient, and extensible
web server.

2.2、httpd2.4安裝常見文件介紹

配置文件:
/etc/httpd/conf/httpd.conf
/etc/httpd/conf.d/*.conf
/etc/httpd/conf.modules.d/*.conf

httpd服務的配置文件:
/etc/sysconfig/httpd

httpd服務的unit文件:
/usr/lib/systemd/system/httpd.service

httpd編譯進的模塊文件:
/usr/lib64/httpd/modules/*.so

httpd程序文件:
/usr/sbin/httpd

httpd日誌文件目錄:
/var/log/httpd/

緩存目錄:
/var/cache/httpd
/var/cache/httpd/proxy

默認主頁文件目錄:
/var/www/html/

2.3、自定義文檔路徑配置資源能實現被訪問

假設自定義的資源路徑爲:/data/web/html
創建目錄:
[root@localhost ~]# mkdir -pv /data/web/html
mkdir: created directory ‘/data’
mkdir: created directory ‘/data/web’
mkdir: created directory ‘/data/web/html’

給系統加一個主機名到ip地址的映射:
[root@www ~]# tail -1 /etc/hosts
172.16.0.77 www.yanhui.com
[root@www ~]# ping www.yanhui.com 
PING www.yanhui.com (172.16.0.77) 56(84) bytes of data.
64 bytes from www.yanhui.com (172.16.0.77): icmp_seq=1 ttl=64 time=0.088 ms
^C
--- www.yanhui.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.088/0.088/0.088/0.000 ms

備份主配置文件:
[root@www ~]# cp /etc/httpd/conf/httpd.conf{,.bak}

修改主配置文件:
添加:
ServerName www.yanhui.com
或者直接寫成
ServerName 172.16.0.77
修改原先配置的DocumentRoot:
修改前:DocumentRoot "/var/www/html"
修改後:DocumentRoot "/data/web/html"

添加一個虛擬主機子配置文件配置文件:
 <VirtualHost *:80>
    DocumentRoot /data/web/html
    <Directory "/data/web/html">
        Options None
        AllowOverride None
        Require all granted
    </Directory>
</VirtualHost>

檢測語法:
[root@www ~]# httpd -t
Syntax OK

防火牆開放http服務:(這次測試只是臨時生效,沒有永久寫入配置文件)
[root@www ~]# firewall-cmd --list-all
public (default, active)
  interfaces: eno16777736
  sources: 
  services: dhcpv6-client ssh
  ports: 
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 
	
[root@www ~]# firewall-cmd --add-service=http
success
[root@www ~]# firewall-cmd --list-all
public (default, active)
  interfaces: eno16777736
  sources: 
  services: dhcpv6-client http ssh
  ports: 
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 

準備一個主頁文件:
[root@www ~]# cat /data/web/html/index.html
<h1>This is a testpage.</h1>

檢查一下資源根目錄apache用戶是否有權限:
[root@www ~]# ls -ld /data/web/html/
drwxr-xr-x 2 root root 23 Dec 21 22:46 /data/web/html/
[root@www ~]# ls -ld /data/web/html/index.html 
-rw-r--r-- 1 root root 29 Dec 21 22:46 /data/web/html/index.html
我們只是測試訪問,目錄和主頁文件對於apache用戶來說都有讀的權限;

#啓動httpd服務:
[root@www ~]# systemctl start httpd.service
[root@www ~]# systemctl status httpd.service
httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled)
   Active: active (running) since Fri 2018-12-21 22:50:03 CST; 5s ago
     Docs: man:httpd(8)
           man:apachectl(8)
 Main PID: 23663 (httpd)
   Status: "Processing requests..."
   CGroup: /system.slice/httpd.service
           ├─23663 /usr/sbin/httpd -DFOREGROUND
           ├─23664 /usr/sbin/httpd -DFOREGROUND
           ├─23665 /usr/sbin/httpd -DFOREGROUND
           ├─23666 /usr/sbin/httpd -DFOREGROUND
           ├─23667 /usr/sbin/httpd -DFOREGROUND
           └─23668 /usr/sbin/httpd -DFOREGROUND

Dec 21 22:50:03 www.yanhui.com systemd[1]: Started The Apache HTTP Server.
[root@www ~]# ss -tnlp|grep :80
LISTEN     0      128                      :::80                      :::*      users:(("httpd",23668,4),("httpd",23667,4),("httpd",23666,4),("httpd",23665,4),("httpd",23664,4),("httpd",23663,4))

在windows瀏覽器測試訪問:
在這裏插入圖片描述

三、yum安裝php-fpm並簡單配置和說明

3.1、yum安裝php-fpm

php-fpm:PHP FastCGI 進程管理器
[root@www ~]# yum info php-fpm
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * epel: mirror01.idc.hinet.net
 * extras: mirrors.cn99.com
 * updates: mirrors.cn99.com
Available Packages
Name        : php-fpm
Arch        : x86_64
Version     : 5.4.16
Release     : 46.el7
Size        : 1.4 M
Repo        : base/7/x86_64
Summary     : PHP FastCGI Process Manager
URL         : http://www.php.net/
License     : PHP and Zend and BSD
Description : PHP-FPM (FastCGI Process Manager) is an alternative PHP FastCGI
            : implementation with some additional features useful for sites of
            : any size, especially busier sites.
CentOS 7上的php-fpm版本是5.4。

安裝php-fpm:
[root@www ~]# yum install php-fpm
...... #安裝過程省略。

[root@www ~]# rpm -ql php-fpm
/etc/logrotate.d/php-fpm
/etc/php-fpm.conf #php-fpm的主配置文件
/etc/php-fpm.d
/etc/php-fpm.d/www.conf #php-fpm的子配置文件
/etc/sysconfig/php-fpm #php-fpm服務的配置文件
/run/php-fpm
/usr/lib/systemd/system/php-fpm.service #php-fpm.service服務的unit文件
/usr/lib/tmpfiles.d/php-fpm.conf
/usr/sbin/php-fpm #php-fpm程序
/usr/share/doc/php-fpm-5.4.16
/usr/share/doc/php-fpm-5.4.16/fpm_LICENSE
/usr/share/doc/php-fpm-5.4.16/php-fpm.conf.default
/usr/share/fpm
/usr/share/fpm/status.html
/usr/share/man/man8/php-fpm.8.gz
/var/log/php-fpm #php-fpm日誌文件目錄

[root@www ~]# rpm -ql php-common
/etc/php.d
/etc/php.d/curl.ini #下面這些也是子配置文件,不過每個配置文件就加入一個擴展,這個是啓用curl擴展模塊的配置文件
/etc/php.d/fileinfo.ini #啓用fileinfo擴展模塊的子配置文件
/etc/php.d/json.ini #啓用json模塊的子配置文件
/etc/php.d/phar.ini #啓用phar模塊的子配置文件
/etc/php.d/zip.ini #啓用zip模塊的子配置文件
/etc/php.ini #php的環境的主配置文件
/usr/lib64/php
/usr/lib64/php/modules #php的模塊路徑
/usr/lib64/php/modules/curl.so
/usr/lib64/php/modules/fileinfo.so
/usr/lib64/php/modules/json.so
/usr/lib64/php/modules/phar.so
/usr/lib64/php/modules/zip.so
/usr/share/doc/php-common-5.4.16
...... #中間省略很多安裝的說明文檔
/usr/share/php
/var/lib/php

3.2、php.ini和php-fpm配置說明

先備份php的配置文件和php-fpm的配置文件:
[root@www ~]# cp /etc/php.ini{,.bak}
[root@www ~]# cp /etc/php-fpm.conf{,.bak}
[root@www ~]# cp /etc/php-fpm.d/www.conf{,.bak}
[root@www ~]# ls -l /etc/php.ini* /etc/php-fpm.conf* /etc/php-fpm.d/www.conf*
-rw-r--r-- 1 root root  1691 Oct 31 03:33 /etc/php-fpm.conf
-rw-r--r-- 1 root root  1691 Dec 21 23:40 /etc/php-fpm.conf.bak
-rw-r--r-- 1 root root 10018 Oct 31 03:33 /etc/php-fpm.d/www.conf
-rw-r--r-- 1 root root 10018 Dec 21 23:40 /etc/php-fpm.d/www.conf.bak
-rw-r--r-- 1 root root 64945 Oct 31 03:33 /etc/php.ini
-rw-r--r-- 1 root root 64945 Dec 21 23:40 /etc/php.ini.bak

php.ini的配置可以參考:
https://my.oschina.net/miaowang/blog/299546
http://www.php.net/manual/zh/ini.php
#本次博文不涉及調整生產環境php.ini的配置,會有專門博文提供此類說明

php-fpm.conf的配置可以參考:
http://www.php.net/manual/zh/install.fpm.php
https://www.cnblogs.com/jonsea/p/5522018.html
https://www.tuicool.com/articles/NjmQNj6
https://blog.csdn.net/l_ieluil/article/details/52808634

默認的php.ini 啓用的配置:
[root@www ~]# grep -Ev '^#|^;|^$' /etc/php.ini
[PHP]
engine = On
short_open_tag = Off
asp_tags = Off
precision = 14
output_buffering = 4096
zlib.output_compression = Off
implicit_flush = Off
unserialize_callback_func =
serialize_precision = 17
disable_functions =
disable_classes =
zend.enable_gc = On
expose_php = On
max_execution_time = 30
max_input_time = 60
memory_limit = 128M
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
display_errors = Off
display_startup_errors = Off
log_errors = On
log_errors_max_len = 1024
ignore_repeated_errors = Off
ignore_repeated_source = Off
report_memleaks = On
track_errors = Off
html_errors = On
variables_order = "GPCS"
request_order = "GP"
register_argc_argv = Off
auto_globals_jit = On
post_max_size = 8M
auto_prepend_file =
auto_append_file =
default_mimetype = "text/html"
doc_root =
user_dir =
enable_dl = Off
file_uploads = On
upload_max_filesize = 2M
max_file_uploads = 20
allow_url_fopen = On
allow_url_include = Off
default_socket_timeout = 60
[CLI Server]
cli_server.color = On
[Date]
[filter]
[iconv]
[intl]
[sqlite]
[sqlite3]
[Pcre]
[Pdo]
[Pdo_mysql]
pdo_mysql.cache_size = 2000
pdo_mysql.default_socket=
[Phar]
[mail function]
SMTP = localhost
smtp_port = 25
sendmail_path = /usr/sbin/sendmail -t -i
mail.add_x_header = On
[SQL]
sql.safe_mode = Off
[ODBC]
odbc.allow_persistent = On
odbc.check_persistent = On
odbc.max_persistent = -1
odbc.max_links = -1
odbc.defaultlrl = 4096
odbc.defaultbinmode = 1
[Interbase]
ibase.allow_persistent = 1
ibase.max_persistent = -1
ibase.max_links = -1
ibase.timestampformat = "%Y-%m-%d %H:%M:%S"
ibase.dateformat = "%Y-%m-%d"
ibase.timeformat = "%H:%M:%S"
[MySQL]
mysql.allow_local_infile = On
mysql.allow_persistent = On
mysql.cache_size = 2000
mysql.max_persistent = -1
mysql.max_links = -1
mysql.default_port =
mysql.default_socket =
mysql.default_host =
mysql.default_user =
mysql.default_password =
mysql.connect_timeout = 60
mysql.trace_mode = Off
[MySQLi]
mysqli.max_persistent = -1
mysqli.allow_persistent = On
mysqli.max_links = -1
mysqli.cache_size = 2000
mysqli.default_port = 3306
mysqli.default_socket =
mysqli.default_host =
mysqli.default_user =
mysqli.default_pw =
mysqli.reconnect = Off
[mysqlnd]
mysqlnd.collect_statistics = On
mysqlnd.collect_memory_statistics = Off
[OCI8]
[PostgreSQL]
pgsql.allow_persistent = On
pgsql.auto_reset_persistent = Off
pgsql.max_persistent = -1
pgsql.max_links = -1
pgsql.ignore_notice = 0
pgsql.log_notice = 0
[Sybase-CT]
sybct.allow_persistent = On
sybct.max_persistent = -1
sybct.max_links = -1
sybct.min_server_severity = 10
sybct.min_client_severity = 10
[bcmath]
bcmath.scale = 0
[browscap]
[Session]
session.save_handler = files
session.use_cookies = 1
session.use_only_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.cookie_httponly =
session.serialize_handler = php
session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
session.bug_compat_42 = Off
session.bug_compat_warn = Off
session.referer_check =
session.cache_limiter = nocache
session.cache_expire = 180
session.use_trans_sid = 0
session.hash_function = 0
session.hash_bits_per_character = 5
url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=fakeentry"
[MSSQL]
mssql.allow_persistent = On
mssql.max_persistent = -1
mssql.max_links = -1
mssql.min_error_severity = 10
mssql.min_message_severity = 10
mssql.compatability_mode = Off
mssql.secure_connection = Off
[Assertion]
[mbstring]
[gd]
[exif]
[Tidy]
tidy.clean_output = Off
[soap]
soap.wsdl_cache_enabled=1
soap.wsdl_cache_dir="/tmp"
soap.wsdl_cache_ttl=86400
soap.wsdl_cache_limit = 5
[sysvshm]
[ldap]
ldap.max_links = -1
[mcrypt]
[dba]

php-fpm.conf主配置文件默認選項:
include=/etc/php-fpm.d/*.conf
[global]
pid = /run/php-fpm/php-fpm.pid
error_log = /var/log/php-fpm/error.log
daemonize = no

php-fpm的子配置文件默認選項:
[root@www ~]# grep -Ev '^#|^$|^;|^ ' /etc/php-fpm.d/www.conf
[www]
listen = 127.0.0.1:9000
listen.allowed_clients = 127.0.0.1
user = apache
group = apache
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
slowlog = /var/log/php-fpm/www-slow.log
php_admin_value[error_log] = /var/log/php-fpm/www-error.log
php_admin_flag[log_errors] = on
php_value[session.save_handler] = files
php_value[session.save_path] = /var/lib/php/session


註解php-fpm.conf: ("#"和";"都可以註釋)
include=/etc/php-fpm.d/*.conf #include指令可以使用多次和任意地方,引入子配置文件

[global] #這種特定格式,以大括號引用,這裏是全局配置部分開始

pid = /run/php-fpm/php-fpm.pid 
#php-fpm進程的pid文件,默認值爲none,不過模板默認值爲前邊/run/php-fpm/php-fpm.pid

error_log = /var/log/php-fpm/error.log 
#定義錯誤日誌文件,默認值爲/var/log/php-fpm.log,這裏有模板默認值爲/var/log/php-fpm/error.log

;log_level = notice 
#定義日誌級別。可選值:alert, error, warning, notice, debug,生產環境不要使用debug,選擇warning或notice
#都行。如果業務量比較大,可以只選擇warning。默認值爲notice

;emergency_restart_threshold = 0
如果emergency_restart_threshold 指定數量的子進程
在emergency_restart_interval指定的時間內以IGSEGV或SIGBUS信號退出,則重啓fpm,
默認0表示關閉這個功能。

;emergency_restart_interval = 0
設置時間間隔來決定服務的初始化時間,平滑重啓(默認單位:s秒),可選單位:
s(econds), m(inutes), h(ours), or d(ays)
秒,分,時,天(單位表示可以縮寫,也可以不縮寫)
默認值:0,默認單位:秒
這對於解決加速器共享內存中的意外損壞很有用。


;process_control_timeout = 0
子進程等待master進程對信號的響應(默認單位:s秒),可選單位:
s(econds), m(inutes), h(ours), or d(ays)
秒,分,時,天(單位表示可以縮寫,也可以不縮寫)
默認值爲:0,默認單位爲:秒

daemonize = no
是否讓php-fpm以守護進程方式後臺運行。設置爲no表示調試的時候使用,正常要設置爲yes。默認值也是yes,
#這裏的模板配置是no,建議改成yes。

進程池的定義在子配置文件:
[www] #這個表示啓動一個新的(進程)池,名字叫www

listen = 127.0.0.1:9000
#指定php-fpm監聽的套接字信息。可以支持指定ip加端口,表示監聽到指定接口的自定端口上。
#也可以只指定一個端口,表示監聽所有網卡接口
#可以指定/path/to/unix/socket,這表示一個unix套接字文件。
#如果php-fpm和httpd安裝到一個主機上,可以採用unix套接字,性能最佳。其次爲了安全,可以監聽到本地迴環
#接口或內網接口。注意,此選項是強制性的,不可省略。

;listen.backlog = -1
#backlog定義掛起隊列的最大長度。可以參考man 2 listen相關說明。默認值爲-1,表示不限制這個隊列長度。

listen.allowed_clients = 127.0.0.1
#允許連接的FastCGI客戶端的ipv4地址列表。多個地址應該以逗號隔開。如果該值留空,表示允許任意地址的客
#戶端連接,默認值爲any表示允許任意地址。這裏的模板配置默認值爲:127.0.0.1
#這個參數設置有講究的,如果訪問php-fpm不是走公網,建議這裏設置好允許連接的客戶端地址,在本機的話,#儘量使用127.0.0.1,如果客戶端與php-fpm不在同一臺服務器,儘量建議走內網。平常使用虛擬機NAT上網做實驗
#的話,要注意瀏覽器實際要通過虛擬網關地址接入,客戶端地址很有可能類似於172.16.0.1這種形式。

;listen.owner = nobody
;listen.group = nobody
;listen.mode = 0666
如果監聽套接字是unix套接字的話,那麼用使用上面這三個參數來定義套接字文件的權限。
默認值:套接字文件屬主和文件屬組設置爲運行進程用戶,mode權限設置爲0666
至少要給php-fpm運行的工作進程用戶讀寫unix套接字的權限。

user = apache
group = apache
#設置php-fpm運行工作進程用戶和組。user選項不可省略。如果省略group選項,會使用user指定用戶的主要組。

pm = dynamic
pm可選值可以爲:static或dynamic,該選項不可省略。
static:固定數量的子進程;使用pm.max_children進行定義固定子進程數量;
dynamic:子進程數量以動態模式進行管理;具體動態和以下指令有關係:
pm.max_children,pm.start_servers ,pm.min_spare_servers,pm.max_spare_servers

pm.max_children = 50
#最大的子進程數量。該選項不可省略。這個值就是併發限制值。

pm.start_servers = 5
#只有當pm設置爲dynamic動態管理時候,該參數纔有用。
#初始啓動,創建php-fpm工作子進程數量。默認值要通過下面的公式換算:
min_spare_servers + (max_spare_servers - min_spare_servers) / 2

pm.min_spare_servers = 5
#期望最少空閒的php-fpm工作進程的數量。只有當pm值設置爲dynamic時候纔有用,而且pm設置爲dynamic時,
#該參數不可省略。

pm.max_spare_servers = 35
#期望最多空閒的php-fpm工作進程的數量。只有當pm值設置爲dynamic時候纔有用,而且pm設置爲dynamic時,
#該參數不可省略。

;pm.max_requests = 500
#設置每個php-fpm工作子進程響應多少次請求後被銷燬,並重新創建新的子進程。
#默認值是0表示不限制其相應多少次請求。有時候使用第三方程序存在內存泄露,定義這個參數
#爲一個合理值,有時候會更好。

;pm.status_path = /status
#設置php-fpm的狀態頁。值必須以前導的"/"正向反斜線符號開始,後邊的字符串可以設置爲合理的任意值。
#儘量不要和php的擴展名同名。默認值沒有設置狀態頁。狀態頁顯示信息含義如下:
accepted conn:指定進程池已經接收了的請求數量;
pool:進程池的名字;
process manager:子進程的管理方式,動態的或靜態的
idle processes:空閒進程數量;
active processes:活躍進程數量;
total processes:空閒進程和活躍進程總數量;
#值刷新說明:"idle processes","active processes","total processes"得值是按照每一秒的頻率去刷新
#的;“accepted conn”的值是實時刷新的。
#輸出格式說明:默認狀態頁的輸出格式是text/plain,還可以指定以html或json格式輸出。如果定義狀態頁參數
#爲/status,請求域名爲www.yanhui.com,那麼輸出不同格式的寫法如下:
http://www.yanhui.com/status
http://www.yanhui.com/status?json
http://www.yanhui.com/status?html


;ping.path = /ping
用於監控FPM狀態的ping URI。定義這個ping URI可能有以下幾種用途:
(1) 可以藉助第三方利用ping URI監控,把FPM的可用性狀態繪製成趨勢圖譜;
(2) 在負載均衡的場景,一當使用ping URI探測不到fpm主機,可以使用相關策略自動移除這個後端的fpm主機;
(3) 觸發告警,發送給相關維護團隊;
#使用說明:值必須要以"/"開頭,後邊的部分不一定要定義成ping,可以定義成其他任意合理字符串。建議
不要和php擴展名同名。默認值沒有設置。

;ping.response = pong
#用於定義響應ping URI的請求,默認響應格式爲text/plain,而且響應報文的狀態碼爲200.默認值爲
#pong。

;request_terminate_timeout = 0
#終止請求超時時間,在worker進程被殺掉之後,提供單個請求的超時間隔。由於某種原因不停止腳本執行時,
#應該使用該選項,0表示關閉不啓用。
php.ini有定義一個選項叫max_execution_time(默認是30秒),如果單個腳本的最大執行時間超過這個定義值,正
常要被kill掉,有些特殊情況可能會導致腳本並未被終止。這裏可選單位爲:
s(econds)(default), m(inutes), h(ours), or d(ays)
默認值爲0表示off,不啓用這種機制。

;request_slowlog_timeout = 0
慢查詢超時時間。如果定義爲0表示off,不定義這個慢查詢超時時間。如果定義成非0的正數值。php的執行程序
超過這個閾值,會記錄到slowlog定義的慢查詢日誌文件中。可用單位爲:
s(econds)(default), m(inutes), h(ours), or d(ays)
默認值爲0;

slowlog = /var/log/php-fpm/www-slow.log
如果定義了request_slowlog_timeout爲非0,那麼這個slowlog是不可少的選項。
定義慢查詢日誌記錄的文件。

;rlimit_files = 1024
定義打開的文件描述符的限制。這個值如果定義的大於系統默認的值,會以系統默認值爲準。
這個選項的默認值等於系統的默認。建議在生產環境要調整系統的最大打開的文件描述符個數,
而且php-fpm的配置文件的這個選項要根據實際情況調大或調小。

;rlimit_core = 0
設置內核對資源的使用限制值,用於內核轉儲。默認值等於系統設置的值。
這裏可以定義爲"unlimited"表示無限制,或定義爲大於等於0的正整數值。

;chroot =
設置chroot路徑,程序一啓動就將其chroot放置到指定的目錄下,該指令值必須是一個絕對路徑
默認值沒有設置。

;chdir = /var/www
在程序啓動時將會改變到指定的位置(這個是相對路徑,相對當前路徑或chroot後的“/”目錄) 
默認值爲當前工作路徑或啓用chroot時候表示當前chroot的根目錄。

;catch_workers_output = yes
將worker進程的標準輸出和標準錯誤輸出 重定向到主要的錯誤日誌記錄中,如果沒有設置,根據FastCGI的指
定,將會被重定向到/dev/null上。默認值爲no

;security.limit_extensions = .php .php3 .php4 .php5
限制FPM執行解析的擴展名。(簡單來說就是php代碼,以什麼格式後綴結尾才被解析成php資源)。
默認值爲:.php

;env[HOSTNAME] = $HOSTNAME
;env[PATH] = /usr/local/bin:/usr/bin:/bin
;env[TMP] = /tmp
;env[TMPDIR] = /tmp
;env[TEMP] = /tmp
定義環境變量的值。php中定義的環境都從當前環境所繼承。默認值爲沒有定義環境變量。(clean env狀態)

附加的php.ini定義(就是在應用web配置中也可以定義php.ini中的部分選項)。這裏定義的是局部部分,生效範圍
默認爲這個工作進程的進程池內。這裏的設置會覆蓋從php.ini全局配置文件定義的選項值。這些指令和PHP 
SAPI類似:
(1 )php_value/php_flag
(2) php_admin_value/php_admin_flag
第一種形式定義的ini的值表示古典定義格式,就是原生態的。可以被php的ini_set的方法調用和修改的;就是
你這裏定義了這種形式的值,在php的代碼中也可以調用ini_set來修改對應(php.ini)選項的值。第一種形式,例如
php_value[session.save_path] = /var/lib/php/session
第二種形式定義的ini的值,不能被php的ini_set方法修改的值所覆蓋。例如:
php_admin_value[error_log] = /var/log/php-fpm/www-error.log

上面兩種形式的value可以換成flag,flag類型的值表示布爾類型的值,可選有效值:
啓用:on,1,yes
不啓用:off,0,no

下面這些啓用值的含義的作用域只是改工作進程池([www]),而且這些選項,會覆蓋從php.ini讀取的配置。其相關
含義可以參考php.ini的註解。上面有講過下面的這些值可以定義爲
php_admin_value[php_admin_options] = value形式或php_admin_flag[php_admin_options] = bool_value
php_value[php_options] = value形式或 php_flag[php_options] = bool_value

小貼士:我這裏只是根據自己的理解總結成這種形式。

;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f [email protected]
;php_flag[display_errors] = off
php_admin_value[error_log] = /var/log/php-fpm/www-error.log
php_admin_flag[log_errors] = on
;php_admin_value[memory_limit] = 128M

php_value[session.save_handler] = files
php_value[session.save_path] = /var/lib/php/session
#創建session目錄,默認值存儲在文件系統的文件,路徑在/var/lib/php/session,所以如果不存在,要創建
#這個目錄,而且要保證php-fpm工作進程用戶要對這個會話目錄要有讀寫權限。

3.3、php-fpm最終配置參考

[root@www ~]# grep -Ev '^;|^#|^$|^ ' /etc/php-fpm.conf
include=/etc/php-fpm.d/*.conf
[global]
pid = /run/php-fpm/php-fpm.pid
error_log = /var/log/php-fpm/error.log
log_level = notice
daemonize = yes

[root@www php]# grep -Ev '^;|^#|^$|^ ' /etc/php-fpm.d/www.conf
[www]
listen = 127.0.0.1:9000
listen.backlog = -1
listen.allowed_clients = 127.0.0.1
user = apache
group = apache
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 15
pm.max_requests = 1000
pm.status_path = /fpm-status
ping.path = /fpm-ping
ping.response = fpm-pong
request_slowlog_timeout = 5s
slowlog = /var/log/php-fpm/www-slow.log
catch_workers_output = yes
security.limit_extensions = .php .php5
php_admin_value[error_log] = /var/log/php-fpm/www-error.log
php_admin_flag[log_errors] = on
php_value[session.save_handler] = files
php_value[session.save_path] = /var/lib/php/session

創建php的session目錄,並設置合理的權限:
[root@www ~]# mkdir  /var/lib/php/session
[root@www ~]# chown apache:apache /var/lib/php/session
[root@www ~]# ls -ld /var/lib/php/session
drwxr-xr-x 2 apache apache 6 Dec 22 11:38 /var/lib/php/session

3.4、啓動php-fpm,並配置站點訪問測試

啓動服務php-fpm服務:
[root@www ~]# systemctl start php-fpm.service
[root@www ~]# systemctl status php-fpm.service
php-fpm.service - The PHP FastCGI Process Manager
   Loaded: loaded (/usr/lib/systemd/system/php-fpm.service; disabled)
   Active: active (running) since Sat 2018-12-22 13:06:04 CST; 3s ago
 Main PID: 27057 (php-fpm)
   Status: "Ready to handle connections"
   CGroup: /system.slice/php-fpm.service
           ├─27057 php-fpm: master process (/etc/php-fpm.conf)
           ├─27058 php-fpm: pool www
           ├─27059 php-fpm: pool www
           ├─27060 php-fpm: pool www
           ├─27061 php-fpm: pool www
           └─27062 php-fpm: pool www

Dec 22 13:06:04 www.yanhui.com systemd[1]: Starting The PHP FastCGI Process Manager...
Dec 22 13:06:04 www.yanhui.com systemd[1]: Started The PHP FastCGI Process Manager.

[root@www ~]# ss -tnlp|grep :9000
LISTEN     0      128               127.0.0.1:9000                     *:*      users:(("php-fpm",27062,0),("php-fpm",27061,0),("php-fpm",27060,0),("php-fpm",27059,0),("php-fpm",27058,0),("php-fpm",27057,6))

[root@www ~]# ps aux|grep php-fpm|grep -v grep
root      27057  0.0  0.4 221332  8520 ?        Ss   13:06   0:00 php-fpm: master process (/etc/php-fpm.conf)
apache    27058  0.0  0.2 221332  4072 ?        S    13:06   0:00 php-fpm: pool www
apache    27059  0.0  0.2 221332  4072 ?        S    13:06   0:00 php-fpm: pool www
apache    27060  0.0  0.2 221332  4072 ?        S    13:06   0:00 php-fpm: pool www
apache    27061  0.0  0.2 221332  4072 ?        S    13:06   0:00 php-fpm: pool www
apache    27062  0.0  0.2 221332  4072 ?        S    13:06   0:00 php-fpm: pool www

配置新httpd的虛擬主機站點:
[root@www ~]# ls -ld /data/web/php/index.php 
-rw-r--r-- 1 root root 23 Dec 22 12:44 /data/web/php/index.php
這裏站點文檔路徑爲:/data/web/php

確認配置文件有載入fcgi模塊:
[root@www ~]# grep 'fcgi' /etc/httpd/conf.modules.d/*.conf
/etc/httpd/conf.modules.d/00-proxy.conf:LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so

子配置:
[root@www ~]# cat /etc/httpd/conf.d/php.conf 
<VirtualHost *:8080>
    DocumentRoot /data/web/php 
    ProxyRequests Off
    ProxyPassMatch ^/(.*\.php)$ fcgi://127.0.0.1:9000/data/web/php/$1

    <Directory "/data/web/php">
        Options None
        AllowOverride None
        Require all granted 
    </Directory>
</VirtualHost>

檢測語法和設置防火牆允許:
[root@www ~]# httpd -t
Syntax OK

[root@www ~]# firewall-cmd --list-all
public (default, active)
  interfaces: eno16777736
  sources: 
  services: dhcpv6-client http ssh
  ports: 
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 
	
[root@www ~]# firewall-cmd --add-port=8080/tcp
success
[root@www ~]# firewall-cmd --list-all
public (default, active)
  interfaces: eno16777736
  sources: 
  services: dhcpv6-client http ssh
  ports: 8080/tcp   #因爲8080不是http協議的標準端口,所以這裏就直接允許tcp的8080開放訪問
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 

重啓或重載httpd服務:
[root@www ~]# systemctl restart httpd.service
[root@www ~]# ss -tnl
State      Recv-Q Send-Q                                           Local Address:Port                                             Peer Address:Port 
LISTEN     0      128                                                  127.0.0.1:9000                                                        *:*     
LISTEN     0      128                                                          *:22                                                          *:*     
LISTEN     0      100                                                  127.0.0.1:25                                                          *:*     
LISTEN     0      128                                                         :::8080                                                       :::*     
LISTEN     0      128                                                         :::80                                                         :::*     
LISTEN     0      128                                                         :::22                                                         :::*     
LISTEN     0      100                                                        ::1:25                                                         :::*   

測試訪問:
在這裏插入圖片描述

四、yum安裝mariadb-server並簡單配置和說明

4.1、安裝mariadb-server

[root@www ~]# yum install mariadb-server php-mysql
...... #安裝過程省略

php-mysql:(php連接mysql數據庫要用到這個軟件包)
[root@www ~]# yum info php-mysql
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * epel: mirrors.aliyun.com
 * extras: mirrors.cn99.com
 * updates: mirrors.cn99.com
Installed Packages
Name        : php-mysql
Arch        : x86_64
Version     : 5.4.16
Release     : 46.el7
Size        : 232 k
Repo        : installed
From repo   : base
Summary     : A module for PHP applications that use MySQL databases
URL         : http://www.php.net/
License     : PHP
Description : The php-mysql package contains a dynamic shared object that will add
            : MySQL database support to PHP. MySQL is an object-relational database
            : management system. PHP is an HTML-embeddable scripting language. If
            : you need MySQL support for PHP applications, you will need to install
            : this package and the php package.

[root@www ~]# rpm -ql php-mysql
/etc/php.d/mysql.ini
/etc/php.d/mysqli.ini
/etc/php.d/pdo_mysql.ini
/usr/lib64/php/modules/mysql.so
/usr/lib64/php/modules/mysqli.so
/usr/lib64/php/modules/pdo_mysql.so

mariadb-server:
[root@www ~]# yum info mariadb-server
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * epel: mirrors.ustc.edu.cn
 * extras: mirrors.cn99.com
 * updates: mirrors.cn99.com
Installed Packages
Name        : mariadb-server
Arch        : x86_64
Epoch       : 1
Version     : 5.5.60
Release     : 1.el7_5
Size        : 58 M
Repo        : installed
From repo   : base
Summary     : The MariaDB server and related files
URL         : http://mariadb.org
License     : GPLv2 with exceptions and LGPLv2 and BSD
Description : MariaDB is a multi-user, multi-threaded SQL database server. It is a
            : client/server implementation consisting of a server daemon (mysqld)
            : and many different client programs and libraries. This package contains
            : the MariaDB server and some accompanying files and directories.
            : MariaDB is a community developed branch of MySQL.
[root@www systemd]# rpm -ql mariadb-server
/etc/logrotate.d/mariadb
/etc/my.cnf.d/server.cnf  #子配置文件
/usr/bin/innochecksum #離線innodb 表文件的一致性檢測工具
/usr/bin/myisam_ftdump 
/usr/bin/myisamchk #MyISAM存儲引擎的表的維護工具
/usr/bin/myisamlog
/usr/bin/myisampack
/usr/bin/mysql_convert_table_format
/usr/bin/mysql_fix_extensions
/usr/bin/mysql_install_db #初始化mysql數據文件目錄的工具
/usr/bin/mysql_plugin #配置mysql服務端插件的工具
/usr/bin/mysql_secure_installation #提高mysql安裝的安裝設置的工具
/usr/bin/mysql_setpermission
/usr/bin/mysql_tzinfo_to_sql
/usr/bin/mysql_upgrade
/usr/bin/mysql_zap
/usr/bin/mysqlbug
/usr/bin/mysqld_multi #管理多個mysql服務實例的工具
/usr/bin/mysqld_safe #mysql服務端啓動腳本
/usr/bin/mysqld_safe_helper 
/usr/bin/mysqldumpslow #慢查詢日誌文件分析工具
/usr/bin/mysqlhotcopy
/usr/bin/mysqltest
/usr/bin/perror
/usr/bin/replace
/usr/bin/resolve_stack_dump
/usr/bin/resolveip
/usr/lib/systemd/system/mariadb.service #mariadb服務的unit文件
/usr/lib/tmpfiles.d/mariadb.conf
/usr/lib64/mysql/INFO_BIN
/usr/lib64/mysql/INFO_SRC
/usr/lib64/mysql/mysqlbug
/usr/lib64/mysql/plugin
......中間省略很多插件模塊
/usr/lib64/mysql/plugin/sql_errlog.so
/usr/libexec/mariadb-prepare-db-dir
/usr/libexec/mariadb-wait-ready
/usr/libexec/mysqld
......中間省略很多文檔文件
/usr/share/mysql/README.mysql-cnf
/usr/share/mysql/errmsg-utf8.txt
/usr/share/mysql/fill_help_tables.sql
/usr/share/mysql/my-huge.cnf
/usr/share/mysql/my-innodb-heavy-4G.cnf
/usr/share/mysql/my-large.cnf
/usr/share/mysql/my-medium.cnf
/usr/share/mysql/my-small.cnf
/usr/share/mysql/mysql_performance_tables.sql
/usr/share/mysql/mysql_system_tables.sql
/usr/share/mysql/mysql_system_tables_data.sql
/usr/share/mysql/mysql_test_data_timezone.sql
/var/lib/mysql #默認mysql數據文件目錄
/var/log/mariadb  #mysql日誌文件目錄
/var/log/mariadb/mariadb.log
/var/run/mariadb #mysql運行進程pid文件目錄

4.2、簡單配置並啓動

[root@www ~]# grep -A4 '\[mysqld\]' /etc/my.cnf.d/server.cnf 
[mysqld]
skip-name-resolve=ON
lower_case_table_names=1
innodb_file_per_table=ON

在上面配置文件的[mysqld]分組後面寫入一下配置:
含義分別爲:
跳過IP地址反向解析;
忽略字符大小敏感;
每個表一個數據文件;

啓動服務:
[root@www ~]# systemctl start mariadb.service
[root@www ~]# systemctl status mariadb.service
mariadb.service - MariaDB database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; disabled)
   Active: active (running) since Sat 2018-12-22 13:52:26 CST; 35s ago
  Process: 27786 ExecStartPost=/usr/libexec/mariadb-wait-ready $MAINPID (code=exited, status=0/SUCCESS)
  Process: 27706 ExecStartPre=/usr/libexec/mariadb-prepare-db-dir %n (code=exited, status=0/SUCCESS)
 Main PID: 27785 (mysqld_safe)
   CGroup: /system.slice/mariadb.service
           ├─27785 /bin/sh /usr/bin/mysqld_safe --basedir=/usr
           └─27983 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --log-error=/var/log/mariadb/ma...

Dec 22 13:52:24 www.yanhui.com mariadb-prepare-db-dir[27706]: MySQL manual for more instructions.
Dec 22 13:52:24 www.yanhui.com mariadb-prepare-db-dir[27706]: Please report any problems at http://mariadb.org/jira
Dec 22 13:52:24 www.yanhui.com mariadb-prepare-db-dir[27706]: The latest information about MariaDB is available at http://mariadb.org/.
Dec 22 13:52:24 www.yanhui.com mariadb-prepare-db-dir[27706]: You can find additional information about the MySQL part at:
Dec 22 13:52:24 www.yanhui.com mariadb-prepare-db-dir[27706]: http://dev.mysql.com
Dec 22 13:52:24 www.yanhui.com mariadb-prepare-db-dir[27706]: Consider joining MariaDB's strong and vibrant community:
Dec 22 13:52:24 www.yanhui.com mariadb-prepare-db-dir[27706]: https://mariadb.org/get-involved/
Dec 22 13:52:25 www.yanhui.com mysqld_safe[27785]: 181222 13:52:25 mysqld_safe Logging to '/var/log/mariadb/mariadb.log'.
Dec 22 13:52:25 www.yanhui.com mysqld_safe[27785]: 181222 13:52:25 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
Dec 22 13:52:26 www.yanhui.com systemd[1]: Started MariaDB database server.
[root@www ~]# ss -tnlp|grep :3306
LISTEN     0      50                        *:3306                     *:*      users:(("mysqld",27983,13))
[root@www ~]# ps aux|grep mysql
mysql     27785  0.0  0.0 115344  1696 ?        Ss   13:52   0:00 /bin/sh /usr/bin/mysqld_safe --basedir=/usr
mysql     27983  1.6  4.0 971412 82748 ?        Sl   13:52   0:00 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64mysql/plugin --log-error=/var/log/mariadb/mariadb.log --pid-file=/var/run/mariadb/mariadb.pid --socket=/var/lib/mysql/mysql.sock
root      28021  0.0  0.0 112640   960 pts/1    S+   13:52   0:00 grep --color=auto mysql

4.3、用戶名和密碼安裝設置

#要在mysql啓動的情況下調用mysql_secure_installation

[root@www ~]# mysql_secure_installation 

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none):   #第一次默認root密碼爲空,回車即可
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

Set root password? [Y/n] Y  #是否設置root登錄密碼,肯定要設置,默認root是mysql的管理員賬號
New password: 
Re-enter new password: 
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB 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? [Y/n] 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? [Y/n] n  #是否禁止root遠程登錄,禁止後只能通過本地迴環或localhost登錄,根據實際需要設置,我這裏就跳過沒有禁止。
 ... skipping.

By default, MariaDB 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? [Y/n] n #是否刪除默認的test數據庫,可以刪也可以不刪,沒有多大意義。
 ... skipping.

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

Reload privilege tables now? [Y/n] y  #是否重新加載權限配置內容到內存中,要加載一起,立即生效權限表的配置
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

4.4、DDL簡單概述和DML簡單概述

DDL一共有這些分類:
在這裏插入圖片描述

DML一共有這些分類:
在這裏插入圖片描述

DDL是數據定義語句;DML是數據維護語句。
入門常用的DDL語句:CREATE, ALTER, DROP, SHOW
入門常用的DML語句:INSERT, DELETE, UPDATE, SELECT

4.5、DDL和DML簡單舉例

(1) 連接數據庫查看幫助信息

連接mysql數據庫,可以使用mysql命令。
語法結構:mysql [options] db_name
常用選項:
-h, --host=name:指定連接的主機名或ip;
 -u, --user=name :指定用於認證mysql數據庫登錄的用戶名;
-p, --password[=name]:指定連接用戶的認證密碼;
-P, --port=#:指定連接mysql實例的端口;
-D, --database=name:指定連接的數據庫;(也可以不使用這個選項後邊直接接單個數據庫)

[root@www ~]# mysql -h127.0.0.1 -uroot -P3306 -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 9
Server version: 5.5.60-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [(none)]> 

MariaDB [(none)]> \h   #輸入的\h可以查看幫助信息

General information about MariaDB can be found at
http://mariadb.org

List of all MySQL commands:
Note that all text commands must be first on line and end with ';'
?         (\?) Synonym for `help'.
clear     (\c) Clear the current input statement. #清楚當前輸入語句
connect   (\r) Reconnect to the server. Optional arguments are db and host.  #重新連接
delimiter (\d) Set statement delimiter.
edit      (\e) Edit command with $EDITOR.
ego       (\G) Send command to mysql server, display result vertically.
exit      (\q) Exit mysql. Same as quit. #退出交互式接口
go        (\g) Send command to mysql server.
help      (\h) Display this help.
nopager   (\n) Disable pager, print to stdout.
notee     (\t) Don't write into outfile.
pager     (\P) Set PAGER [to_pager]. Print the query results via PAGER.
print     (\p) Print current command.
prompt    (\R) Change your mysql prompt.
quit      (\q) Quit mysql. #退出交互式接口
rehash    (\#) Rebuild completion hash.
source    (\.) Execute an SQL script file. Takes a file name as an argument.
status    (\s) Get status information from the server.  #查看狀態信息
system    (\!) Execute a system shell command. #在mysql交互式接口執行系統命令
tee       (\T) Set outfile [to_outfile]. Append everything into given outfile.
use       (\u) Use another database. Takes database name as argument. #切換到指定數據庫
charset   (\C) Switch to another charset. Might be needed for processing binlog with multi-byte charsets.
warnings  (\W) Show warnings after every statement.
nowarning (\w) Don't show warnings after every statement.

For server side help, type 'help contents'


(2) DDL舉例

(a) CREATE
CREATE DATABASE
CREATE TABLE
在mysql接口單獨查看幫助文檔:HELP CREATE DATABASE或HELP CREATE TABLE

創建一個數據庫,名字叫testdb1,字符集爲utf8:
MariaDB [(none)]> CREATE DATABASE IF NOT EXISTS `testdb1` DEFAULT CHARACTER SET utf8;
Query OK, 1 row affected (0.00 sec)

切換到testdb1數據庫,創建一張表叫student,有兩個字段,一個是id,一個是name:
MariaDB [(none)]> USE testdb1
Database changed
MariaDB [testdb1]> CREATE TABLE `student`(id int,name varchar(40));
Query OK, 0 rows affected (0.01 sec)

MariaDB [testdb1]> DESC student
    -> ;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | YES  |     | NULL    |       |
| name  | varchar(40) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

(b) DROP
DROP DATABASE
DROP TABLE
把上面的創建的testdb1數據庫的表student刪除,以及把創建的數據庫testdb1刪除。
MariaDB [testdb1]> DROP TABLE `student`;
Query OK, 0 rows affected (0.01 sec)

MariaDB [testdb1]> DROP DATABASE testdb1;
Query OK, 0 rows affected (0.00 sec)

(c) ALTER 
ALTER DATABASE
ALTER TABLE
創建一個數據庫testdb,使用默認字符集(latin1),然後使用ALTER 語句修改其字符集爲utf8
MariaDB [(none)]> CREATE DATABASE IF NOT EXISTS testdb;
Query OK, 1 row affected (0.00 sec)

MariaDB [(none)]> SHOW CREATE DATABASE testdb\G
*************************** 1. row ***************************
       Database: testdb
Create Database: CREATE DATABASE `testdb` /*!40100 DEFAULT CHARACTER SET latin1 */
1 row in set (0.01 sec)

MariaDB [(none)]> ALTER DATABASE `testdb` DEFAULT CHARACTER SET utf8;
Query OK, 1 row affected (0.00 sec)

MariaDB [(none)]> SHOW CREATE DATABASE `testdb`\G
*************************** 1. row ***************************
       Database: testdb
Create Database: CREATE DATABASE `testdb` /*!40100 DEFAULT CHARACTER SET utf8 */
1 row in set (0.01 sec)

使用testdb數據庫,創建表student默認繼承數據庫的字符集,然後把表student的utf8字符集改成latin1:
MariaDB [(none)]> USE testdb
Database changed
MariaDB [testdb]> CREATE TABLE student(id int,name varchar(20));
Query OK, 0 rows affected (0.01 sec)

MariaDB [testdb]> SHOW CREATE TABLE student\G
*************************** 1. row ***************************
       Table: student
Create Table: CREATE TABLE `student` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

MariaDB [testdb]> ALTER TABLE `student` DEFAULT CHARSET=latin1;
Query OK, 0 rows affected (0.01 sec)               
Records: 0  Duplicates: 0  Warnings: 0

MariaDB [testdb]> SHOW CREATE TABLE student\G
*************************** 1. row ***************************
       Table: student
Create Table: CREATE TABLE `student` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(20) CHARACTER SET utf8 DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)

給表student加上主鍵:
MariaDB [testdb]> ALTER TABLE `student` ADD PRIMARY KEY(id);
Query OK, 0 rows affected (0.02 sec)               
Records: 0  Duplicates: 0  Warnings: 0

MariaDB [testdb]> SHOW CREATE TABLE student\G
*************************** 1. row ***************************
       Table: student
Create Table: CREATE TABLE `student` (
  `id` int(11) NOT NULL DEFAULT '0',
  `name` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)

(3) DML舉例

(a) SELECT
指定字段查詢mysql數據庫的user表。
MariaDB [testdb]> USE mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [mysql]> SELECT host,user,password FROM user;
+-----------+------+-------------------------------------------+
| host      | user | password                                  |
+-----------+------+-------------------------------------------+
| localhost | root | *6AB9DB55EC23A383510F14B21C10FA16561B6A1A |
| 127.0.0.1 | root | *6AB9DB55EC23A383510F14B21C10FA16561B6A1A |
| ::1       | root | *6AB9DB55EC23A383510F14B21C10FA16561B6A1A |
+-----------+------+-------------------------------------------+
3 rows in set (0.00 sec)

(b) INSERT
向student表中一次加入多條記錄:
MariaDB [testdb]> INSERT INTO student(id,name) VALUES(1,'linghuchong'),(2,'yangguo'),(3,'xiaotang');
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

MariaDB [testdb]> SELECT * FROM student;
+----+-------------+
| id | name        |
+----+-------------+
|  1 | linghuchong |
|  2 | yangguo     |
|  3 | xiaotang    |
+----+-------------+
3 rows in set (0.00 sec)

(c) UPDATE
把id爲3的學生的名字修改爲"guojing"
MariaDB [testdb]> UPDATE student SET name='guojing' WHERE id=3;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [testdb]> SELECT * FROM student;
+----+-------------+
| id | name        |
+----+-------------+
|  1 | linghuchong |
|  2 | yangguo     |
|  3 | guojing     |
+----+-------------+
3 rows in set (0.00 sec)

4.6、創建一個用戶用於站點的動態資源動態登錄

(1) 安裝php
yum install php

(2) 測試數據庫的php代碼1
[root@www php]# cat query.php 
<?php

$mysqli = new mysqli("127.0.0.1","root","yanhui.com","testdb",3306);

if (mysqli_connect_error()) {
    echo "Could not connect to the database.";
    exit ;
}

echo $mysqli->host_info . "\n";

?>

(3) 測試數據庫的php代碼2
[root@www php]# cat nquery.php 
<?php

$mysqli = new mysqli("127.0.0.1","root","yanhui.com","testdb",3306);

if (mysqli_connect_error()) {
    echo "Could not connect to the database.";
    exit ;
}

#echo $mysqli->host_info . "\n";
$result=$mysqli->query("SELECT id,name FROM student");
while( $row=$result->fetch_row() )
{
    echo $row[0]."======".$row[1];
    echo "\n";
}

?>
[root@www php]# php nquery.php 
1======linghuchong
2======yangguo
3======guojing

(4) 爲了支持html格式,特地加入了一些元素
[root@www php]# cat select.php 
<?php
$db_host = '127.0.0.1';        //使用的主機名稱
$db_user = 'root';        //使用的數據庫用戶名
$db_pwd = 'yanhui.com';        //使用的數據庫密碼
$db_name ='testdb';    //使用的數據庫名稱
$db_port = 3306; //使用數據庫的端口
$conn = mysqli_connect($db_host, $db_user, $db_pwd, $db_name, $db_port)or die("鏈接失敗".mysqli_error());
 
$sql = "select id,name from student";
echo('<table>');
if($res=mysqli_query($conn, $sql)){
    while ($row= mysqli_fetch_array($res)){
        echo '<tr><td>'.$row[0].'</td><td class="sno">'.$row[1].'</td><td class="cno">'.$row[2].'</td><td class="score">'.$row[3].'</td><td class="create_time">'.$row[4].'</td><td>'.$row[5].'</td></tr>';
    }
}
echo('</table>');
?>

測試結果:
在這裏插入圖片描述

上面講到的處理動態資源都是利用php-fpm來處理,現在我們使用php的模塊來處理:

確保php軟件有安裝。如果沒有執行:yum install php
[root@www conf.d]# rpm -ql php
/etc/httpd/conf.d/php.conf   #爲httpd調用php模塊準備的配置文件
/etc/httpd/conf.modules.d/10-php.conf #加載模塊的配置文件愛你
/usr/lib64/httpd/modules/libphp5.so #這個是最重要的,就是php的模塊,可以直接處理
/usr/share/httpd/icons/php.gif
/var/lib/php/session

模仿/etc/httpd/conf/d/php.conf準備了一份虛擬主機配置,微調了一下:
[root@www conf.d]# cat /etc/httpd/conf.d/vhost2.conf 
Listen 8080
<VirtualHost *:8080>
    DocumentRoot /data/web/php 
    DirectoryIndex index.php index.html
    <FilesMatch \.php$>
        SetHandler application/x-httpd-php
    </FilesMatch>
    AddType text/html .php
    php_value session.save_handler "files"
    php_value session.save_path    "/var/lib/php/session"
    <Directory "/data/web/php">
        Options None
        AllowOverride None
        Require all granted 
    </Directory>
</VirtualHost>
下面會截圖我們之前寫的select.php等文件。

停止php-fpm,重啓httpd服務:
systemctl stop php-fpm.service
httpd -t
systemctl restart httpd.service

在這裏插入圖片描述

在這裏插入圖片描述

五、使用開源軟件wordpress搭建博客平臺並實現簡單的訪問

wordpress下載列表:
https://cn.wordpress.org/download/releases/

這一部分我們利用php的模塊來直接處理動態內容。

解壓wordpress的軟件包,然後拷貝重命名blog到站點目錄(/data/web/html):
[root@www tmp]# pwd
/var/tmp
[root@www tmp]# ls
systemd-private-QfxXKM  systemd-private-YwqxhJ  wordpress-4.7.4-zh_CN.tar.gz  yum-root-VeNnpu
[root@www tmp]# tar -xf wordpress-4.7.4-zh_CN.tar.gz 
[root@www tmp]# ls
systemd-private-QfxXKM  systemd-private-YwqxhJ  wordpress  wordpress-4.7.4-zh_CN.tar.gz  yum-root-VeNnpu
[root@www tmp]# cp -ar wordpress /data/web/html/blog

修改權限後,頁面訪問:
[root@www html]# ls -l
total 12
drwxr-xr-x 5 nobody 65534 4096 Apr 23  2017 blog
-rw-r--r-- 1 root   root    35 Dec 22 16:00 hello.php
-rw-r--r-- 1 root   root    23 Dec 22 15:51 index.php
[root@www html]# chown -R apache:apache blog
[root@www html]# ls -l
total 12
drwxr-xr-x 5 apache apache 4096 Apr 23  2017 blog
-rw-r--r-- 1 root   root     35 Dec 22 16:00 hello.php
-rw-r--r-- 1 root   root     23 Dec 22 15:51 index.php

初始訪問截圖:
http://172.16.0.77/blog #要設置主頁文件index.php
在這裏插入圖片描述

根據頁面提示,我們直接去調整blog下的wp-config.php文件(複製一份wp-config-sample.php到wp-config.php):

[root@www html]# cd /data/web/html/blog/
[root@www blog]# ls -l wp-config.php
ls: cannot access wp-config.php: No such file or directory
[root@www blog]# cp wp-config-sample.php wp-config.php

修改前:

// ** MySQL 設置 - 具體信息來自您正在使用的主機 ** //
/** WordPress數據庫的名稱 */
define('DB_NAME', 'database_name_here');

/** MySQL數據庫用戶名 */
define('DB_USER', 'username_here');

/** MySQL數據庫密碼 */
define('DB_PASSWORD', 'password_here');

/** MySQL主機 */
define('DB_HOST', 'localhost');

/** 創建數據表時默認的文字編碼 */
define('DB_CHARSET', 'utf8');


修改後:
// ** MySQL 設置 - 具體信息來自您正在使用的主機 ** //
/** WordPress數據庫的名稱 */
define('DB_NAME', 'web_blog');

/** MySQL數據庫用戶名 */
define('DB_USER', 'blog');

/** MySQL數據庫密碼 */
define('DB_PASSWORD', 'BLOG1234blog*');

/** MySQL主機 */
define('DB_HOST', '127.0.0.1');

/** 創建數據表時默認的文字編碼 */
define('DB_CHARSET', 'utf8');

去數據庫授權用戶,並登錄測試後創建對應數據庫:
授權語句(這裏爲了方便就給一個ALL權限):
GRANT ALL ON web_blog.* TO blog@'127.0.0.1' IDENTIFIED BY 'BLOG1234blog*';
CREATE DATABASE IF NOT EXISTS  `web_blog` DEFAULT CHARACTER SET utf8;

MariaDB [(none)]> GRANT ALL ON web_blog.* TO blog@'127.0.0.1' IDENTIFIED BY 'BLOG1234blog*';
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> CREATE DATABASE IF NOT EXISTS  `web_blog` DEFAULT CHARACTER SET utf8;
Query OK, 1 row affected (0.00 sec)

MariaDB [(none)]> SELECT host,user,password FROM mysql.user;
+-----------+------+-------------------------------------------+
| host      | user | password                                  |
+-----------+------+-------------------------------------------+
| localhost | root | *6AB9DB55EC23A383510F14B21C10FA16561B6A1A |
| 127.0.0.1 | root | *6AB9DB55EC23A383510F14B21C10FA16561B6A1A |
| ::1       | root | *6AB9DB55EC23A383510F14B21C10FA16561B6A1A |
| 127.0.0.1 | blog | *338B01CA4946C78F9E8BB1616DB01AA0AC18D418 |
+-----------+------+-------------------------------------------+
4 rows in set (0.00 sec)

測試訪問:
[root@www blog]# mysql -h127.0.0.1 -ublog -P3306 -p --default-character-set=utf8 web_blog 
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 8
Server version: 5.5.60-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [web_blog]> SHOW TABLES;
Empty set (0.00 sec)

MariaDB [web_blog]> 

在這裏插入圖片描述

在這裏插入圖片描述

在這裏插入圖片描述

在這裏插入圖片描述

在這裏插入圖片描述

在這裏插入圖片描述

在這裏插入圖片描述

在這裏插入圖片描述

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章