HostOnNet Blog

PHP can’t connect to MySQL running on localhost

Looking for Linux Server Admin or WordPress Expert? We can help.

On a server, PHP can’t connect to MySQL with following code, it returned error “Could not connect: Permission denied 2002”


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

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

If i change “localhost” with IP address 127.0.0,1, PHP script is able to connect to MySQL server properly.

If i run the script from command line, it was able to connect to MySQL using localhost.

When you use localhost to connect from PHP script, you will be using socket instead of TCP Port 3306. Socket is faster than using TCP connection.

To verify, i run following command in command line.

[root@server1 ~]# php -r 'var_dump(mysql_connect("localhost:/var/lib/mysql/mysql.sock", "user", "password"));'
resource(5) of type (mysql link)
[root@server1 ~]#

As you can see, we get “mysql link”, that means we are able to connect.

On CentOS 7 server, PHP/Apache run as user “apache”, it look like problem with user apache. So first we need to login as user apache and run above command to see if it work for user apache. By default system users like apache have SSH disabled. So enable it with command

chsh apache --shell /bin/bash

Now lets login as user apache and run the above command

[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

It fails. Lets see if user apache can access mysql.sock

-bash-4.2$ ls -l /var/lib/mysql/mysql.sock
ls: cannot access /var/lib/mysql/mysql.sock: Permission denied

Apache user can’t access the MySQL socket.

The problem is resolved by setting 755 permission for folder /var/lib/mysql

chmod 755 /var/lib/mysql

Now lets disable shell access for user apache like it was before.

chsh --shell /sbin/nologin apache


[root@3blogger lib]# chsh --shell /sbin/nologin apache
Changing shell for apache.
Shell changed.
[root@3blogger lib]# 

Posted in MySQL

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.