Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

php - PDO connection works from command line, but not through Apache?

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. :-(

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)".

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Note that httpd_can_network_connect may not be necessary. Try it first turning on only httpd_can_network_connect_db.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...