Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Php PDO can connect to a mysql database on command line but not on my apache webserver. Why?

I am running this script:

<? php

try {
        $db = new PDO("mysql:host=127.0.0.1;dbname=mydb;port=3306","user","pass");
        var_dump($db);
} catch (Exception $e) {
        echo "Could not connect to the database.";
        exit;
)
echo "Awww Yeeaa";
?>

When I run in command line I am able to connect. I get the output:

$ php database.php

object(PDO)#1 (0) {}

Awww Yeeaa

BUT in the browser (http://127.0.0.1/database.php) when I access the file I get:

Could not connect to the database.

Why is this happening? I have run phpinfo; and it tells me this about PDO:

PDO

PDO support => enabled

PDO drivers => mysql, sqlite

pdo_mysql

PDO Driver for MySQL => enabled

Client API version => 5.1.73

Halp.

2 Answers

Found the answer here: http://stackoverflow.com/questions/8139451/pdo-connection-works-from-command-line-but-not-through-apache

I should have mentioned I'm on a CentOS box. Apparently on Red Hat derived linux distros the default policy is to prevent webservers from making connections to databases or other servers.

As root you must run:

setsebool -P httpd_can_network_connect=1

setsebool -P httpd_can_network_connect_db=1

instead of 127.0.0.1 can you try localhost instead?? I know it means the same thing but worth a try. Cant see anything wrong with your code.

Tried it out. Unfortunately no difference.