前言


在linux上放置php代码,发现启动httpd后访问php页面报错:

1
Warning: mysql_connect(): Can't connect to MySQL server on 'xxx'

即php无法连接至指定的数据库,在谷歌、百度查找许久后,终于在谷歌一篇文章中寻找到了类似的疑问与解答。

如果您正在寻找解决方案而我的解决方案对您不起作用,我将列出最常见的解决方案:
1–确保正确配置了MySQL用户权限。
2–确保MySQL在服务器上和正确的端口上运行
3–确保selinux不会阻止MySQL端口或mysqld进程

前两点相信大家都能明白是怎么回事,也不会在这点上犯错,但是第三点,selinux,这是什么?

SELinux


SELinux是一个 Linux 内核模块,也是 Linux 的一个安全子系统。它的作用简而言之就是最大限度地减小系统中服务进程可访问的资源。在这里,很显然就是SELinux限制了httpd对mysql的访问。

默认情况下,大部分系统的 SELinux 设置为 Enforcing。你要如何知道你的系统当前是什么模式?你可以使用一条简单的命令来查看,这条命令就是 getenforce。如下图:

getenforce.png

可以很明显地看到,SELinux的状态为Enforcing。
SELinux的状态:
1)enforcing:强制状态,每个受限的进程都必然受限
2)permissive:启用状态,每个受限的进程违规操作不会被禁止
3)disabled:关闭状态

设置 SELinux 的模式实际上很简单——取决于你想设置什么模式。记住:永远不推荐关闭 SELinux。最佳模式是 Enforcing 或者 Permissive。

enforcing 和 permissive 模式可以通过 setenforce 1|0 命令快速切换。

1
2
[root@localhost ~]# setenforce 0
[root@localhost ~]# setenforce 1

setenforce.png

解决方法


首先切换SELinux的模式:

1
[root@localhost ~]# setenforce 0;

然后使用setsebool命令,它是用来修改SElinux策略内各项规则的布尔值。即:

1
[root@localhost ~]# setsebool -P httpd_can_network_connect_db 1

至此,重新启动httpd,再次访问php页面即可。

附部分setsebool命令与用途:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
setsebool -P allow_ftpd_anon_write=1          #允许ftpd匿名用户可写
setsebool -P ftp_home_dir 1 #允许用户访问自己的根目录
setsebool -P ftpd_is_daemon 1 #允许daemon运行ftpd
setsebool -P ftpd_disable_trans 1 #关闭SELINUX对ftpd的保护
setsebool -P allow_httpd_anon_write=1 #允许httpd匿名用户可写
setsebool -P allow_httpd_sys__anon_write=1 #同上
setsebool -P httpd_enable_cgi 1 #httpd被设置允许cgi被执行
setsebool -P httpd_enable_homedirs 1 #允许访问用户的根目录
setsebool -P httpd_tty_comm 1 #允许httpd控制终端
setsebool -P httpd_unified 0 #httpd之间相互独立
setsebool -P httpd_builtin_ing 0 #同httpd环境一样运行
setsebool -P httpd_can_network_connect_db 1 #httpd可以连接到数据库(如连接mysql就必须设置)
setsebool -P httpd_can_network_connect 1 #httpd可以连接到网络(如连接redis就必须设置)
setsebool -P httpd_read_user_content 1 #开启用户文件的访问权限(如日志文件就必须设置)
setsebool -P httpd_suexec_disable_trans 1 #禁用suexec过度
setsebool -P httpd_disable_trans 1 #允许daemon用户启动httpd
setsebool -P httpd_can_sendmail 1 #允许httpd发送email
setsebool -P named_write_master_zones 1 #允许修改dns的主zone文件
setsebool -P named_disable_trans 1 #允许daemon启动named
setsebool -P nfs_export_all_ro 1 #nfs只读
setsebool -P nfs_export_all_rw 1 #nfs可读写
setsebool -P use_nfs_home_dirs 1 #允许本机访问远程nfs的根目录
setsebool -P allow_smbd_anon_write=1 #samba允许匿名用户可写
setsebool -P samba_enable_home_dirs 1 #允许根目录访问
setsebool -P use_samba_home_dirs 1 #允许本机访问远程samba根目录
setsebool -P smbd_disable_trans 1 #允许daemon启动samba
setsebool -P allow_rsync_anon_write=1 #允许匿名用户可写
setsebool -P rsync_disable_trans 1 #允许daemon启动rsync