10

I am trying to connect the database with the following script(cxn-test.php)

<?php
$host = '155.30.136.20';//dummy ip 
$user = 'abc_user';
$pass = 'xxxxxxxxx';
$dbname = 'welcome';
$link = mysqli_connect($host, $user, $pass,$dbname);
if (!$link) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}else {
    echo "success" . PHP_EOL;
}

When I am trying on the terminal

php cxn-test.php //success

But when I am trying on localhost i am getting the following error,

curl -s http://localhost/cxn-test.php

Error: Unable to connect to MySQL. Debugging errno: 2002 Debugging error: Permission denied

This is strange issue it's not working on the localhost but working good on command line.

ajreal
  • 46,720
  • 11
  • 89
  • 119
Sundar
  • 4,580
  • 6
  • 35
  • 61

1 Answers1

44

I had the same issue after getting a new CentOS 7 box, running SELinux. I could connect to my remote MySQL DB server from the command line, but Drupal (and test PHP scripts) could not.

The issue turned out to be the SELinux security policies.

By default, the policy httpd_can_network_connect_db is disabled (meaning that your web server cannot contact a remote DB.)

Check this via:

getsebool -a | grep httpd

If httpd_can_network_connect_db is Off, enable it via:

setsebool -P httpd_can_network_connect_db 1

(The -P flag makes the change permanent, so the setting survives a reboot.)

Sundar
  • 4,580
  • 6
  • 35
  • 61
Charlie
  • 456
  • 5
  • 4
  • 4
    Nice, +1 for not telling people to turn off SELinux! – miken32 Mar 10 '17 at 05:48
  • 1
    I had same issue which only got fixed by disabling SELinux. Thanks for your comment for highlighting it – ankit9j Apr 27 '17 at 21:59
  • Work like a charm. Kudos to you. – ajreal Jun 20 '18 at 12:19
  • Took me FOREVER to find this (using Redhat). Thank you so much. – Richard Mar 19 '19 at 23:49
  • For anyone trying to connect remotely from a Digital Ocean droplet to an AWS instance, this was necessary on the droplet in addition to these steps on the instance: https://stackoverflow.com/questions/9766014/connect-to-mysql-on-amazon-ec2-from-a-remote-server – HWD May 07 '20 at 23:10