skip to Main Content

I know this is a bit unusual question, but I am looking for a way to execute code like this:

$conn = mysqli_connect('localhost', 'root', null, 'mydb');

And instead of going to UNIX socket connection I would like it to use TCP. I know this can be done by changing localhost to 127.0.0.1 but is there a way to use localhost as host and get the same result? Through some kind of configuration etc?

To clarify further I am asking – Is there a way to configure PHP, OS or whatever to change how connection to mysql database is made through mysqli_connect in such way that when ‘localhost’ is used as host php interprets it as TCP connection and not as UNIX socket connection?

2

Answers


  1. Chosen as BEST ANSWER

    There is actually a way to solve this problem (on Linux). I discovered tool called socat that is capable of proxying the unix socket to TCP and vice versa.

    What I did was following:

    1. Configured php.ini to contain this setting

      mysqli.default_socket = "/run/mysqld/mysqld.sock"
      
    2. Created directory /run/mysqld

    3. Initiated socat process

      socat UNIX-LISTEN:/run/mysqld/mysqld.sock,fork,reuseaddr,unlink-early,user=root,group=root,mode=777 TCP:127.0.0.1:3306 &
      
    4. And then it all started working


  2. The manual says:

    The TCP/IP protocol is used if a host name and port number are
    provided together e.g. localhost:3308.

    See: https://www.php.net/manual/en/mysqli.construct.php

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search