Database connection error: Error type 2002 - Permission denied
P粉757640504
2023-08-24 19:54:00
<p>I am trying to connect to the database using the following script (cxn-test.php)</p>
<pre class="brush:php;toolbar:false;"><?php
$host = '155.30.136.20';//Virtual 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 "Debug error number:" . mysqli_connect_errno() . PHP_EOL;
echo "Debug error message:" . mysqli_connect_error() . PHP_EOL;
exit;
}else {
echo "success" .PHP_EOL;
}</pre>
<p>When I try it on the terminal</p>
<blockquote>
<p>php cxn-test.php //Success</p>
</blockquote>
<p>But when I try it on localhost, I get the following error: </p>
<blockquote>
<p>curl -s http://localhost/cxn-test.php</p>
</blockquote>
<p><code>Error: Unable to connect to MySQL.
Debug error number: 2002
Debug error message: Permission denied</code></p>
<p>This is a weird issue, it doesn't work on localhost but works fine on the command line. </p>
I ran into the same problem after getting a new CentOS 7 box running SELinux. I can connect to the remote MySQL database server via the command line, but Drupal (and the test PHP script) cannot connect.
The problem is ultimately caused by the SELinux security policy.
By default, the policy httpd_can_network_connect_db is disabled (meaning your web server cannot contact the remote database).
Check with the following command:
getsebool -a | grep httpd
If httpd_can_network_connect_db is Off, please enable it through the following command:
(The -P flag makes the changes permanent, so the settings remain in effect across reboots.)