【问题标题】:php can't connect to mysql with error 13 (but command line can)php 无法连接到 mysql 并出现错误 13(但命令行可以)
【发布时间】:2011-05-03 22:54:13
【问题描述】:

我在新安装的服务器中出现了奇怪的情况,这次谷歌似乎无法帮助我。 我无法从我的 php 代码连接到(远程)mysql。当我尝试从同一服务器上的命令行连接时,连接成功。

无法连接:无法连接到 'MYSQL.SERVER' 上的 MySQL 服务器 (13)

这是代码和来自命令行的连接尝试

[u1@bosko httpdocs]$ cat  test.php

<?
$link = mysql_connect('MYSQL.SERVER', 'testusersimon', '123456');
if (!$link) {
    die('Could not connect: ' .  mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

[u1@bosko httpdocs]$ mysql -h MYSQL.SERVER -utestusersimon --password=123456
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 352108
Server version: 5.0.45-community-nt-log MySQL Community Edition (GPL)

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license

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

mysql> quit
Bye

我尝试在 mod_php 模式和 FastCGI 中运行 php 脚本, 检查“/etc/php.d/mysql.ini”是否出现在 phpinfo() 以及 mysql、mysqli 和 pdo_mysql 部分中。

但结果是一样的,我知道这很简单,但我就是做不到。 请帮忙:)

编辑: 问题出在 SElinux 上

setsebool -P httpd_can_network_connect_db=1

是解决方案。

【问题讨论】:

  • Fedora11远程服务器是Win2k8

标签: php apache


【解决方案1】:

在带有 apache 2/httpd 版本 2.6 的 Fedora 21 上,当连接到远程 mysql 服务器 5.6 或 mariadb 版本 10 时使用 php 版本 5.6。在指定服务器的 FQDN 而不是 localhost 时,连接到本地服务器甚至似乎是一个问题php代码。

此命令将修复当前会话的权限问题:

setsebool httpd_can_network_connect_db on

要使修复在后续重新启动时永久生效,您需要执行以下操作:

setsebool -P httpd_can_network_connect_db on

感谢所有关于这个问题的人将我从“权限被拒绝”的地狱中解救出来。 :)

【讨论】:

    【解决方案2】:

    在 CentOs 6 上,您可以使用以下内容(不带 -P)

    setsebool httpd_can_network_connect=1
    

    【讨论】:

      【解决方案3】:
      setsebool -P httpd_can_network_connect=1
      

      对于许多访问此问题的人来说也是一个有用的 CLI 命令,因为允许 mysql_connet() 从 HTTP (Apache) 请求中连接到远程 MySQL 数据库服务器,确保在 SElinux 中启用来自 httpd 的网络连接,通常位于/etc/selinux/config(默认禁用以防止黑客使用您的 httpd 攻击其他机器)。

      【讨论】:

      • 正如我在之前的评论中所说 - 这确实与 SELinux 相关。
      • 尝试命令行时它可以工作,但是当 Apache 执行它时,错误是“警告:mysql_connect():[2002] 权限被拒绝(尝试通过 tcp://w.x.y.z:3306 连接)”。是的,它与 SELinux 有关。真的,我们尝试了很多不同的东西。非常感谢@thesimon
      • 我经常关闭 selinux,以至于每次看到与 selinux 相关的权限错误时我都认不出来。谢谢你的线索。
      • 大声笑,这些 SElinux 问题。文件夹访问 apache 半天。现在半天用于数据库连接。
      • MacOS 的修复怎么样?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      • 2015-04-19
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      相关资源
      最近更新 更多