MySQL php can’t connect to localhost, 127.0.0.1 working

apache-2.4MySQLPHP

I have a Simple PHP script, that is not able to connect to MySQL.

<?php

$link = mysql_connect("localhost", "user", "password");

if (!$link) {
    die('Could not connect: ' . mysql_error() . ' ' . mysql_errno());
} else {
    echo "connected";
}

When i access the page with url

http://mydomain/1.php

I get error

Could not connect: Permission denied 2002

If i change "localhost" with "127.0.0.1", it works.

If i run the program from command line, for example

php 1.php

it connects. To verify the problem, i run

[root@server1 ~]# php -r 'var_dump(mysql_connect("localhost:/var/lib/mysql/mysql.sock", "user", "password"));'
resource(5) of type (mysql link)
[root@server1 ~]# chsh apache --shell /bin/bash
Changing shell for apache.
chsh: Shell not changed.
[root@server1 ~]# su - apache
Last login: Fri Mar 17 02:30:39 CDT 2017 on pts/0
-bash-4.2$ php -r 'var_dump(mysql_connect("localhost:/var/lib/mysql/mysql.sock", "user", "password"));'
PHP Warning:  mysql_connect(): Permission denied in Command line code on line 1
bool(false)
-bash-4.2$ ls -l /var/lib/mysql/mysql.sock
ls: cannot access /var/lib/mysql/mysql.sock: Permission denied
-bash-4.2$ 

How do i fix this issue, this is CentOS 7 server with default php version. MySQL version is

[root@server1 ~]# mysql --version
mysql  Ver 15.1 Distrib 5.5.52-MariaDB, for Linux (x86_64) using readline 5.1
[root@server1 ~]# 

EDIT:

This is CentOS 7 Server, SELinux is disabled.

# sestatus
SELinux status:                 disabled
# 

Best Answer

I had the same problem a few hours ago (cpanel & cloudlinux)

My simple solution was to modify /etc/my.cnf:

[root@ds1 home]# cat /etc/my.cnf
[mysqld]
innodb_file_per_table=1
default-storage-engine=MyISAM
performance-schema=0
max_allowed_packet=268435456
open_files_limit=28574
#bind-address=127.0.0.1
bind-address=localhost

local-infile=0
[client]
socket=/var/lib/mysql/mysql.sock
host=localhost

[root@ds1 home]#