問題描述
我有一個非常簡單的測試腳本:
I have a very simple test script:
<?php
$DSN = "mysql:host=db.example.edu;port=3306;dbname=search_data";
try {
$DB = new PDO($DSN, "username", "super-secret-password!");
} catch (PDOException $e) {
header('Content-Type: text/plain');
print "Could not connect to database, rawr. :-(";
exit;
}
$SQL = "SELECT phrase FROM search ORDER BY RAND() LIMIT 10";
foreach($DB->query($SQL) as $row){
print $row['phrase']."
";
}
?>
當我從命令行執行此腳本時,它運行良好:
When I execute this script from the command line, it works perfectly:
$ php test.php
corporal punishment
Stretches
voluntary agencies and the resettlement of refugees
music and learning
Nike Tiger Woods Scandal
Hermeneia
PSYCHINFO
anthony bourdain
Black-White Couples and their Social Worlds
colonization, hodge
但是當我通過網絡瀏覽器訪問完全相同的腳本時,它說:
But when I access the exact same script through my web browser, it says:
Could not connect to database, rawr. :-(
我已經嘗試了 var_dump
解決錯誤,消息是:SQLSTATE[HY000] [2003] 無法連接到 MySQL 服務器上的 'db.example.edu' (13)".
I've tried var_dump
on the error, and the message is: "SQLSTATE[HY000] [2003] Can't connect to MySQL server on 'db.example.edu' (13)".
這令人費解.這是完全相同的服務器上的完全相同的腳本——為什么當我從命令行執行它時它可以工作,但當 Apache 執行它時卻失敗?
This is puzzling. It's the exact same script on the exact same server -- why does it work when I execute it from the command line, but fail when Apache executes it?
推薦答案
如果這是運行 SELinux(或任何使用 SELinux 的任何非 Red Hat 衍生產品)的 Red Hat 衍生發行版(RHEL、CentOS、Fedora、ScientificLinux),則默認撰寫本文時的策略設置是禁止 Apache 與其他服務器或數據庫建立外部連接.作為 root,您必須啟用以下兩個 SELinux 布爾值.使用 -P
選項在重新啟動后保持更改.
If this is a Red Hat-derived distribution (RHEL, CentOS, Fedora, ScientificLinux) running SELinux (or any non Red Hat derivative using SELinux), the default policy setting at time of this writing is to prohibit Apache from making external connections to other servers or databases. As root, you must enable the following two SELinux booleans. Use the -P
option to persist the change across a reboot.
setsebool -P httpd_can_network_connect=1
setsebool -P httpd_can_network_connect_db=1
請注意,httpd_can_network_connect
可能不是必需的.首先嘗試僅打開 httpd_can_network_connect_db
.
Note that httpd_can_network_connect
may not be necessary. Try it first turning on only httpd_can_network_connect_db
.
這篇關于PDO 連接從命令行工作,而不是通過 Apache?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!