1

I am trying to run some php scripts that we use at my company to do some data analysis. These scripts do things that require root access, so I have no choice but to run them with sudo.

I have narrowed down the issues I'm having to connecting to the database as root vs. my own user. I have the following super stripped down code just to show the issue:

<?php

// mydatabasename, myUsername, myPassword are replaced with the real names, everything else is the same

$pdo = new PDO('mysql:host=localhost;dbname=mydatabasename', 'myUsername', 'myPassword', array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
var_dump($pdo);
?>

When I run this script without sudo, it works just fine. When I run it with sudo, I get the following error:

 Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' in /opt/.../something.php:5

I'm not sure what's going on here, and I don't have a super advanced knowledge of PHP or MySQL. the file /var/run/mysqld/mysqld.sock does not exist on our server. I'm not sure why root would be trying to access it but my user wouldn't.

jchitel
  • 2,999
  • 4
  • 36
  • 49
  • Have you seen this Q? https://stackoverflow.com/questions/5376427/cant-connect-to-local-mysql-server-through-socket-var-mysql-mysql-sock-38 There might be something helpful there. – Don't Panic Jun 06 '17 at 20:51
  • So the issue seems to be something to do with where php will look for the lock file. When I run it as my own user, it uses the correct location (we have our LAMP stack installed to a different location than the normal default), but for some reason root is looking in a different place. – jchitel Jun 06 '17 at 21:08
  • Could be a permissions problem if `/var/run/mysqld` isn't public readable. – tadman Jun 06 '17 at 21:21
  • `/var/run/mysqld` doesn't exist. `/var/run` is a symlink to `/run`, which root (and only root) has full permissions over. – jchitel Jun 06 '17 at 21:57
  • You either need to give permissions, or store that file somewhere else. It's configurable in `/etc/my.cnf` or equivalent. – tadman Jun 06 '17 at 21:59
  • So, we keep our LAMP stack under `/opt/lampp/`. The `my.cnf` file is under `/opt/lampp/etc/my.cnf`, which has a socket config pointing to `/opt/lampp/var/mysql/mysql.sock`, which seems to be the "correct" location. However, there is an `/etc/mysql/my.cnf` which has the socket configured to `/var/run/mysqld/mysqld.sock`. What specifies the configuration file to use? – jchitel Jun 06 '17 at 22:24

0 Answers0